Python Syntax - Comprehensive Study Notes

Introduction to Python Syntax

  • Python syntax is the set of rules that define how to write code so the interpreter can understand it.
  • Syntax is to programming what grammar is to natural languages: it determines whether statements are valid or not.
  • Common programming concepts like using = for assignment exist across languages, but Python has its own peculiarities (no $, no need for ;, no {} blocks).
  • The syntax is only part of programming; writing correct programs also requires understanding how the language behaves (semantics), not just how it looks.
  • For example, Python code can be read like pseudo-code thanks to its readable syntax.
  • A simple example demonstrates variables, arithmetic, and conditional printing: the following Python code defines integers a, b, c, computes a result, and prints it when a flag is True.
# Definimos una variable x con una cadena
x = "The value of (a+b) * c is"
# Podemos realizar múltiples asignaciones a, b, c
a, b, c = 4, 3, 2
# Realizamos unas operaciones con a,b,c
d = (a + b) * c
# Definimos una variable booleana
print_enabled = True
# Si imprimir, print()
if print_enabled:
    print(x, d)
  • Salida esperada: The value of (a+b) * c is 14.
  • This example shows that Python syntax is close to natural language, aiding readability.
  • Important: no need for a main() function in Python to run scripts.

Comments

  • Single-line comments start with # and extend to the end of the line.
    • Example: # This is a comment.
  • Multi-line comments can be created with triple quotes: ''' ... ''' or """ ... """.
    • This is commonly used for multi-line notes or docstrings, not executed as code.
    • Example: ''' This is a multi-line comment '''.
  • Comments are not code and do not affect execution, but they help future readers.

Indentation and blocks of code

  • Python uses indentation to define blocks of code; there are no braces {} like in C/Java.
  • The standard is to use four spaces per indentation level.
  • A block starts after statements that introduce a new block (e.g., if, for, def).
  • Example showing a simple if with an indented block:
if True:
    print("True")
  • An empty if block is a syntax error; you must provide a block of code under the if.
  • Unlike some languages, you typically do not end lines with ; in Python; it’s optional unless you want multiple statements on one line.
  • You can place multiple statements on the same line using ;:
x = 5; y = 10
  • Python also allows breaking long lines into multiple lines:
    • Use a backslash \ to indicate line continuation for a single statement across lines.
    • Or break lines inside parentheses, brackets, or braces, which does not require \.
# Backslash continuation
x = 1 + 2 + 3 + 4 +\
    5 + 6 + 7 + 8

# Continuation inside parentheses
x = (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8)
  • PEP 8 recommends lines not exceeding 79 characters for readability.

Creating variables

  • Variables are created with assignment using =:
    • Simple assignment: x = 10.
    • Multiple assignment (same value): x = y = z = 10.
    • Tuple unpacking / multiple values: x, y = 4, 2 and x, y, z = 1, 2, 3.
  • Variable names are case-sensitive: x and X are different variables.

Naming variables

  • Rules and conventions:
    • A name cannot start with a digit.
    • Hyphens - and spaces are not allowed in names.
    • Names should be descriptive but concise; Python is case-sensitive.
  • Examples of valid names:
    • _variable = 10
    • vari_able = 20
    • variable10 = 30
    • variable = 60
    • variaBle = 10
  • Examples of invalid names:
    • 2variable = 10
    • var-iable = 10
    • var iable = 10
  • Avoid Python reserved words (keywords) as variable names. To see the list of keywords you can run:
import keyword
print(keyword.kwlist)
  • Example output (keywords):
    • ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Operators and precedence; arithmetic operators

  • Python supports the common arithmetic operators: addition +, subtraction -, multiplication *, division /, exponentiation **, etc.
  • Exponentiation uses the operator ** (e.g., 3 ** 2 is 9).
  • Example demonstrating operator usage and precedence:
x = 10
y = x * 3 - 3 ** 10 - 2 + 3
  • Precedence matters: parentheses alter evaluation order.
  • With parentheses:
x = 10
y = (x * 3 - 3) ** (10 - 2) + 3
  • This shows how parentheses can be used to enforce the intended order of operations.

Variables: scope (global vs local)

  • The scope (visibility) of a variable depends on where it is defined.
  • In the following example, the global x remains 10 even though a local x is defined inside the function:
x = 10

def funcion():
    x = 5

funcion()
print(x)  # Output: 10
  • The x inside funcion is a local variable; it does not modify the global x unless declared with global.
  • Understanding scope is important when designing functions and modules.

The print() function

  • print() is used to display output to the screen and can print text, variables, or a combination:
print("This is the content to print")
print(x)
print("The values x, y are:", x, y)  # prints text and variables separated by spaces
  • Using comma-separated arguments in print() prints with spaces between items.
  • Printing helps debug and observe how values change during execution.

Practical considerations and real-world relevance

  • Python’s syntax emphasizes readability and simplicity, which lowers the learning curve and helps collaboration.
  • Indentation rules promote clean, uniform code style and reduce syntax clutter.
  • Understanding comments, blocks, and line continuation aids in maintaining and debugging code in real projects.
  • Knowing how to declare variables, manage names, and respect keywords prevents common runtime errors.
  • Grasping operator precedence and scope is essential for writing correct and predictable functions.

Connections to broader concepts and practical implications

  • Syntactic rules set the foundation for productive programming; semantics determine behavior and outcomes.
  • The absence of a main() function in Python reflects its scripting and module-focused philosophy, enabling rapid experimentation and reuse of code.
  • Comments and docstrings are critical for maintainability, especially in team settings or long-term projects.
  • Line length and readability guidelines (e.g., PEP 8) help teams keep code approachable and consistent.

Summary of key takeaways

  • Python syntax relies on indentation for blocks, not braces; use four spaces per level.
  • Use # for single-line comments and triple quotes for multi-line comments/docstrings.
  • Variables are created via assignment; multiple values can be assigned at once, and names are case-sensitive.
  • Valid variable names must avoid starting with digits, hyphens, and spaces; avoid reserved keywords.
  • Arithmetic and logical operators follow precedence, with ** for exponentiation and () to control order.
  • The print() function is versatile for debugging and user-facing output.
  • Global vs local scope matters; assignments inside a function create local variables unless specified otherwise.
  • Python allows breaking long lines with \ or by wrapping inside parentheses; aim for readable line lengths.
  • There are practical resources to deepen understanding of functions, scope, and advanced topics beyond syntax.