Getting Started

Python Basic Syntax

Learn the fundamental syntax rules of Python including indentation, comments, statements, and code structure.

Python Basic Syntax

Python's syntax is designed to be clean and readable. Unlike many other languages, Python uses indentation to define code blocks instead of curly braces. Understanding these fundamental syntax rules is essential for writing correct Python code.


Indentation

Indentation is mandatory in Python. It defines code blocks for functions, loops, conditions, and classes. The standard is 4 spaces per indentation level.

python
# Correct indentation
if True:
    print("This is indented correctly")
    if True:
        print("This is nested correctly")

# Wrong indentation - causes IndentationError!
if True:
print("This will cause an error")  # IndentationError

Important: Never mix tabs and spaces. Configure your editor to use 4 spaces for indentation.


Comments

Comments make your code easier to understand. Python ignores all comments during execution.

Single-line Comments

python
# This is a single-line comment
name = "Python"  # This is an inline comment

Multi-line Comments

Python doesn't have a dedicated multi-line comment syntax, but you can use triple quotes:

python
"""
This is a multi-line comment.
It spans across multiple lines.
Often used as docstrings for functions and classes.
"""

'''
You can also use single quotes
for multi-line comments.
'''

Docstrings

Docstrings are special comments that document functions, classes, and modules:

python
def greet(name):
    """
    Greets a person by name.

    Args:
        name (str): The name of the person to greet.

    Returns:
        str: A greeting message.
    """
    return f"Hello, {name}!"

# Access the docstring
print(greet.__doc__)

Variables and Naming

Python variables don't need type declarations:

python
# Variable assignment
name = "Alice"
age = 25
height = 5.7
is_student = True

Naming Rules

RuleValidInvalid
Start with letter or underscorename, _count1name, @value
Contain letters, digits, underscoresmy_var_2my-var, my var
Case-sensitiveNamename
Not a reserved keywordmy_classclass, if, for

Naming Conventions

python
# Variables and functions: snake_case
user_name = "Alice"
def calculate_total():
    pass

# Constants: UPPER_SNAKE_CASE
MAX_RETRIES = 3
PI = 3.14159

# Classes: PascalCase
class UserAccount:
    pass

# Private: prefix with underscore
_internal_value = 42

# "Really" private: prefix with double underscore
__very_private = "secret"

The print() Function

python
# Basic printing
print("Hello, World!")

# Multiple values
print("Name:", "Alice", "Age:", 25)
# Output: Name: Alice Age: 25

# Custom separator
print("2026", "02", "15", sep="-")
# Output: 2026-02-15

# Custom end character (default is newline)
print("Hello", end=" ")
print("World")
# Output: Hello World

# f-strings (formatted string literals)
name = "Alice"
age = 25
print(f"{name} is {age} years old")
# Output: Alice is 25 years old

The input() Function

python
# Basic input
name = input("Enter your name: ")
print(f"Hello, {name}!")

# Input is always a string - convert as needed
age = int(input("Enter your age: "))
height = float(input("Enter your height: "))

print(f"In 10 years you'll be {age + 10}")

Statements and Line Continuation

Single Statement Per Line

python
# One statement per line (preferred)
x = 10
y = 20
total = x + y

Multiple Statements on One Line

python
# Using semicolons (not recommended)
x = 10; y = 20; total = x + y

Line Continuation

python
# Implicit continuation inside brackets
numbers = [
    1, 2, 3,
    4, 5, 6,
    7, 8, 9
]

# Explicit continuation with backslash
total = 1 + 2 + 3 + \
        4 + 5 + 6 + \
        7 + 8 + 9

# Long conditions
if (age >= 18 and
    has_license and
    not is_suspended):
    print("Can drive")

Python Keywords

Python has 35 reserved keywords that cannot be used as variable names:

python
import keyword
print(keyword.kwlist)
CategoryKeywords
LogicTrue, False, None, and, or, not, is, in
Control Flowif, elif, else, for, while, break, continue, pass
Functionsdef, return, lambda, yield
Classesclass
Exceptiontry, except, finally, raise, assert
Importimport, from, as
Scopeglobal, nonlocal
Otherwith, del, async, await

Type Checking

Use type() to check a variable's type:

python
x = 42
print(type(x))  # <class 'int'>

y = "hello"
print(type(y))  # <class 'str'>

z = [1, 2, 3]
print(type(z))  # <class 'list'>

# isinstance() for type checking
print(isinstance(x, int))     # True
print(isinstance(y, str))     # True
print(isinstance(z, (list, tuple)))  # True

Complete Example

python
"""
A simple program demonstrating Python basic syntax.
"""

# Constants
GREETING = "Welcome to Python!"

# Function with docstring
def introduce(name, age):
    """
    Creates an introduction message.

    Args:
        name (str): Person's name
        age (int): Person's age

    Returns:
        str: Introduction message
    """
    return f"Hi, I'm {name} and I'm {age} years old."

# Main program
if __name__ == "__main__":
    print(GREETING)
    print("-" * 30)

    # Get user input
    user_name = input("What's your name? ")
    user_age = int(input("How old are you? "))

    # Display introduction
    message = introduce(user_name, user_age)
    print(message)

    # Conditional logic
    if user_age >= 18:
        print("You are an adult.")
    else:
        print("You are a minor.")

Summary

  • Python uses indentation (4 spaces) to define code blocks — it's mandatory
  • Comments use # for single-line and """ for multi-line/docstrings
  • Variables don't need type declarations — Python is dynamically typed
  • Use snake_case for variables/functions, PascalCase for classes, UPPER_CASE for constants
  • print() outputs text, input() reads user input (always returns a string)
  • Python has 35 reserved keywords that can't be used as identifiers
  • Use type() and isinstance() to check variable types

Next, we'll dive into Python variables in detail.