Python Syntax Fundamentals

Python's syntax is known for its "readability and simplicity", often resembling plain English. It emphasizes clear, logical code structure.

Here's a breakdown of some fundamental Python syntax elements:


Indentation and Blocks

Unlike many other programming languages that use curly braces ({}) to define blocks of code, "Python uses indentation". This is one of its most distinctive features.

if 5 > 2:
    print("Five is greater than two!") # This line is inside the if-block
    print("The condition is true.")
# This line is outside the if-block

Comments

Comments are used to explain code and are ignored by the Python interpreter.

Single-line Comments

# This is a single-line comment
x = 10 # Everything after the '#' is a comment

Docstrings (Documentation Strings)

Docstrings are typically used for multi-line comments or to explain the purpose of modules, functions, classes, and methods. They are enclosed in "triple quotes" (""" or ''').

def multiply(a, b):
    """
    This function takes two numbers and returns their product.
    This is a docstring.
    """
    return a * b

Variables and Data Types

age = 30         # int (integer)
name = "Alice"   # str (string)
is_student = True # bool (boolean)
pi_value = 3.14  # float (floating-point number)

Basic Statements and Flow Control

Conditional Statements (if, elif, else)

Used for making decisions in your code.

score = 85

if score >= 90:
    print("A")
elif score >= 80: # 'elif' is Python's shorthand for 'else if'
    print("B")
else:
    print("C")

Loops (for, while)

Used to execute a block of code repeatedly.

for loop

Iterates over a sequence (like a list, tuple, dictionary, set, or string).

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

while loop

Executes a set of statements as long as a condition is true.

count = 1
while count <= 5:
    print(count)
    count = count + 1

Functions

Functions are blocks of reusable code defined using the keyword "def".

def greet(person):
    """Greets the person passed in as argument."""
    message = "Hello, " + person + "!"
    return message

greeting_result = greet("Bob")
print(greeting_result) # Output: Hello, Bob!