TutorialsPythonPython Syntax
Share:

Python Syntax

beginner

Part of Python Basics

Theory

Python's syntax emphasizes readability. Unlike many languages that use curly braces or keywords, Python uses indentation to define code blocks. This forces clean, consistent formatting.

Indentation rules: All statements in a block must have the same indentation level. The standard is 4 spaces per level. Mixing tabs and spaces causes IndentationError. Indentation is required after colon-terminated headers like if, def, for, while, class, with, and try.

Comments start with # and extend to the end of the line. There are no multi-line comment syntaxes in Python, but triple-quoted strings ("""...""" or '''...''') are often used as multi-line comments or docstrings even though they're technically string literals.

Docstrings document modules, functions, classes, and methods. Enclosed in triple quotes, they appear as the first statement in a definition and are accessible via help() and __doc__.

Variables don't require explicit type declaration. Python infers the type from the assigned value. Variable names must start with a letter or underscore, followed by letters, digits, or underscores. They are case-sensitive (name and Name differ).

Naming conventions follow PEP 8:

  • snake_case for variables, functions, and modules
  • PascalCase for classes
  • UPPER_CASE for constants
  • Single leading underscore _var for internal/private use
  • Double leading underscore __var for name mangling

Basic I/O:

  • print() outputs to the console. It supports multiple arguments, custom separators (sep), end characters (end), and file output (file)
  • input() reads a line from the user as a string. Convert with int(), float(), etc. for numeric input

Multiple assignment is a Python feature: a, b = 1, 2 assigns 1 to a and 2 to b. It also enables swapping: a, b = b, a.

Python Syntax Basics
python
Indentation and Blocks
python

Exercises

Personal Info Formatter

easy

Write a Python program that asks the user for their name, age, and favorite color using input(). Then print a formatted sentence: 'Hello [name]! You are [age] years old and your favorite color is [color].'

Starter Code:

# Get user input and print a formatted sentence

Expected Output:

Hello Alice! You are 25 years old and your favorite color is blue.

Mini Quiz

Mini Quiz