python-indentacion-comentarios

Basic Python Syntax

  • 3 min

Code in Python is divided into lines, which we call statements. A statement is an instruction that the Python interpreter can execute (such as assignments, expressions, flow control declarations, etc.).

Python is an interpreted language, meaning that the code will be executed line by line through an interpreter.

Each statement will contain operations, control structures, data manipulation (we will see each point in the following articles).

An example of a statement would be like this,

x = 5
Copied!

In this example, x = 5 is an assignment statement that assigns the value 5 to the variable x.

Indentation in Python

In Python, indentation is used to define the structure and blocks of code (unlike other languages that use braces {} to delimit blocks).

Indentation involves inserting spaces or tabs at the beginning of lines of code to indicate the belonging of one block to another.

There are different conventions for adding indentation. Probably the most common convention in Python is to use 4 spaces for each level of indentation.

In the end, one or the other is the same. What is important is to maintain consistency in the indentation of your code (that is, always use the same format).

Example of Indentation in Python

Let’s see an example illustrating the use of indentation to delimit code blocks.

# Variable declaration
x = 5
y = 10

# Function definition
def sum(a, b):
    # Indented code block
    result = a + b
    return result

# Control structure
if x < y:
    # Indented code block
    print("x is less than y")
else:
    # Another indented code block
    print("y is less than x")
Copied!

In this example, you can observe how indentation spaces are used to delimit blocks both in a function and in a conditional if.

If you want to learn more, check out the Introduction to Programming Course

Comments in Python

Comments in Python are a way to add notes or explanations in the code. They are created using the # symbol.

Everything after # on the same line is treated as a comment and will not be executed.

# This is a comment in Python
Copied!

Comments are useful for making code more understandable for other programmers or for yourself in the future.

If you want to learn more, check out the Introduction to Programming Course

Reserved Words

Reserved words are terms that have a specific meaning and are reserved by the language for its internal use. These words cannot be used as identifiers (names of variables, functions, etc.).

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
Copied!