Python Syntax
beginnerPart 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_casefor variables, functions, and modulesPascalCasefor classesUPPER_CASEfor constants- Single leading underscore
_varfor internal/private use - Double leading underscore
__varfor 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 withint(),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.
Exercises
Personal Info Formatter
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 sentenceExpected Output:
Hello Alice! You are 25 years old and your favorite color is blue.