Python Syntax

Python syntax is designed to be simple and easy to read. Indentation plays a crucial role in defining the structure of Python code. Unlike many other programming languages, Python does not use braces to delimit code blocks; instead, it uses indentation.

Hello World Example

One of the simplest and most common programs in Python is the Hello World program. This program outputs the text "Hello, World!" to the console.

# Hello World Example
print("Hello, World!")

Output

Hello, World!

Key Points about Python Syntax

  • Python uses indentation to define blocks of code.
  • Statements are typically ended by a newline and do not require semicolons.
  • Variables are dynamically typed, so there is no need to explicitly declare their type.
  • Python is case-sensitive, meaning that variable and Variable are treated as different names.

Common Syntax Errors

Below are some common syntax errors that beginners may encounter in Python.

Error 1: Incorrect Indentation

# Incorrect indentation
if True:
print("This will raise an indentation error.")

Output

IndentationError: expected an indented block

Explanation: Python uses indentation to define code blocks. The print statement in this example is not indented, which leads to an IndentationError. You must indent all code inside control statements like if.

Corrected Code

# Corrected indentation
if True:
    print("This block is now indented correctly.")

Output

This block is now indented correctly.

Explanation: The corrected code now properly indents the print() statement under the if statement, resolving the error.

Error 2: Missing Colon in Control Statements

# Missing colon in control statement
if True
    print("This will raise a syntax error.")

Output

SyntaxError: invalid syntax

Explanation: Python requires a colon : at the end of control statements such as if, for, and while. The lack of a colon in this code results in a SyntaxError.

Corrected Code

# Corrected control statement with colon
if True:
    print("This block will now execute correctly.")

Output

This block will now execute correctly.

Explanation: The corrected code includes the missing colon : after the if True statement, allowing the code to execute correctly.

Error 3: Case Sensitivity

# Case sensitivity error
Variable = "Python"
print(variable)

Output

NameError: name 'variable' is not defined

Explanation: Python is case-sensitive. In this example, Variable and variable are treated as two different variables. Since variable is not defined, a NameError occurs.

Corrected Code

# Corrected case sensitivity
variable = "Python"
print(variable)

Output

Python

Explanation: The corrected code uses consistent case for the variable names, ensuring that variable is properly defined and can be printed.