Basic Syntax and Structure of the Python Language

Python is known for its simplicity and readability, making it an excellent choice for both beginners and experienced programmers.
Below, we’ll explore the fundamentals of its syntax and structure.


1. Main Features of Python Syntax

Mandatory Indentation:

Python uses indentation to define code blocks instead of braces {} or keywords like begin and end.
It’s essential to use the same number of spaces or tabs at each indentation level.

if True:
    print("This block is correctly indented")

Case Sensitivity:

Python distinguishes between uppercase and lowercase letters, so variables like name and Name are different.

End of Line as End of Statement:

In Python, you don’t need to use a semicolon ; to end a statement (though it’s allowed if you do).


2. Comments

Comments begin with the # symbol. They are used to document code and are ignored by the interpreter.

# This is a comment
print("Hello, world")  # This prints a message to the screen

For multi-line comments, you can use triple quotes (""" or ''').

"""
This is a comment
that spans multiple lines.
"""

3. Variables and Data Types

Declaring Variables:

You don’t need to declare variable types; Python infers them automatically.

age = 25          # Integer
name = "Ana"      # String
price = 19.99     # Float
is_active = True  # Boolean

Basic types:

  • int (integers)
  • float (decimal numbers)
  • str (text strings)
  • bool (boolean values: True or False)

4. Basic Program Structure

Input:

name = input("What is your name? ")
print(f"Hello, {name}!")  # Using f-strings

Conditionals:

age = int(input("How old are you? "))
if age >= 18:
    print("You are an adult.")
else:
    print("You are underage.")

Loops:

For loop:

for i in range(5):
    print(f"Iteration {i}")

While loop:

counter = 0
while counter < 3:
    print(f"Counter: {counter}")
    counter += 1

5. Functions

Python allows you to define functions using the def keyword.

def greet(name):
    return f"Hello, {name}!"

message = greet("John")
print(message)

6. Error Handling

The try-except structure is used to handle exceptions.

try:
    number = int(input("Enter a number: "))
    print(f"The double of {number} is {number * 2}")
except ValueError:
    print("Please enter a valid number.")

7. Importing Modules

You can use modules to extend the language’s functionality.

import math

root = math.sqrt(16)
print(f"The square root of 16 is {root}")