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.
# 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") # IndentationErrorImportant: 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
# This is a single-line comment
name = "Python" # This is an inline commentMulti-line Comments
Python doesn't have a dedicated multi-line comment syntax, but you can use triple quotes:
"""
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:
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:
# Variable assignment
name = "Alice"
age = 25
height = 5.7
is_student = TrueNaming Rules
| Rule | Valid | Invalid |
|---|---|---|
| Start with letter or underscore | name, _count | 1name, @value |
| Contain letters, digits, underscores | my_var_2 | my-var, my var |
| Case-sensitive | Name ≠ name | — |
| Not a reserved keyword | my_class | class, if, for |
Naming Conventions
# 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"Print and Input
The print() Function
# 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 oldThe input() Function
# 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
# One statement per line (preferred)
x = 10
y = 20
total = x + yMultiple Statements on One Line
# Using semicolons (not recommended)
x = 10; y = 20; total = x + yLine Continuation
# 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:
import keyword
print(keyword.kwlist)| Category | Keywords |
|---|---|
| Logic | True, False, None, and, or, not, is, in |
| Control Flow | if, elif, else, for, while, break, continue, pass |
| Functions | def, return, lambda, yield |
| Classes | class |
| Exception | try, except, finally, raise, assert |
| Import | import, from, as |
| Scope | global, nonlocal |
| Other | with, del, async, await |
Type Checking
Use type() to check a variable's type:
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))) # TrueComplete Example
"""
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()andisinstance()to check variable types
Next, we'll dive into Python variables in detail.