Posted in

Basic Python Syntax – The Foundation for Entering the World of Python Programming

Basic Python Syntax

In today’s technological world, Python has become one of the most popular and influential programming languages. From artificial intelligence, data analysis, and web development to automation, Python is widely used across these fields. One of the key factors behind Python’s remarkable success is its clear, easy-to-read, and easy-to-write syntax, making it suitable for both beginners and experienced developers.

Mastering the basic syntax of Python is the first but extremely important step. It serves as the foundation that allows you to move on to more advanced concepts such as variables, data types, control structures, and object-oriented programming. Without a solid understanding of the syntax, you may easily encounter small errors that prevent your program from running or make it difficult to maintain in the long run.

In this article, we will systematically explore the fundamental syntax rules in Python, while also highlighting key considerations for writing clean, efficient, and “Pythonic” code.

1. Getting Started with Python

Interactive mode và Script mode

Python supports two ways of running programs:

  • Interactive mode: You enter commands directly into the terminal or environments such as IDLE or Jupyter Notebook, and the results are returned immediately. This approach is very convenient for quick experiments or step-by-step learning.
C:\Users\kienthucmo> python
Python 3.10.6 (tags/v3.10.6:somehash, Jul 20 2022, 18:00:00) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print ("Hello KienThucMo")
  • Script mode: You write code in a .py file and then run it using the command python file.py. This approach is suitable for longer programs or projects.

For example, create a file named hello.py with the following content:

print ("Hello KienThucMo")

Both approaches produce the same output:

Hello KienThucMo

When starting out, you can begin with the interactive mode to get familiar with the syntax, and then switch to script mode to develop code organization skills.

2. Indentation and Formatting Rules

One of the most significant differences between Python and languages such as C, Java, or JavaScript is that Python does not use curly braces {} to define code blocks. Instead, Python uses indentation.

if 5 > 2:
    print("Five is greater than two!")

If you omit indentation or indent incorrectly, Python will raise an IndentationError.

Standard Rules

  • Use 4 spaces for indentation (PEP 8).
  • Do not mix tabs and spaces.
  • Most modern IDEs/editors support automatic indentation configuration.

Common Errors

  • Inconsistent indentation.
  • Forgetting the : at the end of statements such as if, for, while, def, and class.

3. Multi-line Statements

Python allows line breaks in two ways:

  1. Using the backslash \:
x = 1 + 2 + 3 + \
    4 + 5 + 6

2. Enclosing within parentheses (), brackets [], or braces {}:

x = (1 + 2 + 3 +
     4 + 5 + 6)

The second approach is recommended because it is more concise and less error-prone.

4. Strings and Representation

In Python, strings can be written using:

  • '...' or "..." for single-line strings.
  • '''...''' or """...""" for multi-line strings.
s1 = "KienThucMo"
s2 = '''This is
a multi-line
string.'''

f-string

Starting from Python 3.6, f-strings allow you to easily insert variables into strings:

name = "KienThucMo"
print(f"Hello, {name}")

This is the recommended syntax to use instead of .format() or %.

5. Comments and Documentation in Code

Comments help others (and your future self) understand the code more easily.

  • Single-line comments: use #.
  • Multi-line comments: use docstrings """ ... """.

Example:

def greet(name):
    """Hàm này nhận tên và in lời chào"""
    print("Hello,", name)  # In ra màn hình

According to PEP 257, docstrings should describe the purpose of a function, class, or module.

6. Blank Lines and Code Style

Python ignores blank lines when executing code, but they improve readability.

  • According to PEP 8:
    • Use two blank lines between functions/classes.
    • Use one blank line to separate logic within a function.

Example:

def add(a, b):
    return a + b


def subtract(a, b):
    return a - b

7. Taking Input from Users

Python provides the input() function to receive user input:

name = input("Enter your name: ")
print("Hello,", name)

Note: input() always returns a string. If you want to work with numbers:

age = int(input("Enter your age: "))

8. Multiple Statements on One Line

You can write multiple statements on a single line using the ; separator.

a = 1; b = 2; print(a + b)

However, Python encourages one statement per line for better readability.

9. Statement Blocks

In Python, code blocks are defined by indentation. For example with if...else:

if x > y:
    print("x is greater than y")
    print("Comparison successful")
else:
    print("y is greater than or equal to x")

10. Command-line Arguments

Python provides the sys module to access command-line arguments via sys.argv.

Example:

import sys

print("File name:", sys.argv[0])
for i in range(1, len(sys.argv)):
    print("Argument", i, ":", sys.argv[i])

Run:

python test.py arg1 arg2

Result:

File name: `test.py`
Argument 1: `arg1`
Argument 2: `arg2`

Application: Writing utility scripts that accept parameters from users.

11. Important Notes

  • Python is strict about indentation, so use 4 spaces.
  • Write code according to PEP 8 standards to ensure consistency.
  • Prefer clarity over brevity (the principle of “Readability counts”).
  • Avoid writing multiple statements on a single line.
  • Learn syntax together with practice: open the Python console and try each example.

Conclusion

Basic syntax is the “common language” you must master to communicate with Python. Only by understanding how Python reads and interprets code can you avoid common errors and develop clean, readable, and maintainable coding habits.

A major difference of Python lies in its simplicity: no complex braces, no mandatory semicolons, but clear indentation instead. Thanks to this, Python has become one of the most popular languages for both beginners and professionals.

After mastering the basic syntax, the next step is to continue learning advanced concepts and practicing regularly.

References

Leave a Reply

Your email address will not be published. Required fields are marked *