Python Syntax

Learn the basic syntax rules and structure of Python programming.

Execute Python Syntax

As we learned in the previous page, Python syntax can be executed by writing directly in the Command Line:

>>> print("Hello, World!")
Hello, World!

Or by creating a Python file on the server, using the .py file extension, and running it in the Command Line:

C:\Users\Your Name>python myfile.py

Python Indentation

Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important.

Python uses indentation to indicate a block of code.

Example

if 5 > 2:
    print("Five is greater than two!")

Python will give you an error if you skip the indentation:

Example (This will give an error)

if 5 > 2:
print("Five is greater than two!")

The number of spaces is up to you as a programmer, the most common use is four, but it has to be at least one.

Example

if 5 > 2:
 print("Five is greater than two!") 
if 5 > 2:
        print("Five is greater than two!")

You have to use the same number of spaces in the same block of code, otherwise Python will give you an error:

Example (This will give an error)

if 5 > 2:
 print("Five is greater than two!")
        print("Five is greater than two!")

Python Variables

In Python, variables are created when you assign a value to it:

Example

x = 5
y = "Hello, World!"

Python has no command for declaring a variable. You will learn more about variables in the Python Variables chapter.

Comments

Python has commenting capability for the purpose of in-code documentation. Comments start with a #, and Python will render the rest of the line as a comment:

Example

# This is a comment
print("Hello, World!")

Indentation Is Not Optional

Where other languages use braces, Python uses indentation to mark a block. Every line in the same block must be indented the same amount. The community standard (PEP 8) is 4 spaces per level — never mix tabs and spaces.

if 5 > 2:
    print("Five is greater than two")   # 4-space indent = inside the if

# IndentationError: expected an indented block
# if 5 > 2:
# print("no indent")

Mixing tabs and spaces raises TabError. Configure your editor to insert spaces when you press Tab.

Statements, Lines, and Continuation

One statement per line is the norm. Break a long line with a backslash \, or — better — wrap it in parentheses, which continue automatically.

total = (1 + 2 + 3 +
         4 + 5)          # parentheses continue the line

x = 1; y = 2             # two statements on one line (allowed, discouraged)

Try It Yourself

Exercise 1: Write an if that prints "Big" when a variable n is greater than 100.

Show solution
n = 150
if n > 100:
    print("Big")

Exercise 2: The code below has an indentation bug. Fix it.

if True:
print("hi")
Show solution
if True:
    print("hi")     # indent the body by 4 spaces

Key Takeaways

  • Indentation defines blocks — use 4 spaces, consistently.
  • One statement per line; wrap long lines in parentheses.
  • Never mix tabs and spaces.

📘 Real-World Deep Dive

Indentation is Python's block delimiter. Most "weird" bugs come from mixing tabs/spaces or from a misplaced colon, so internalising the grammar once pays off forever.

Real-Life Scenario

A small predicate that decides whether a CSV record should be ingested.

Real-Life Example

def looks_like_a_user(row: dict) -> bool:
    return (
        row.get("email")
        and "@" in row["email"]
        and row.get("signup_date") >= "2025-01-01"
        and int(row.get("age", 0)) >= 18
    )

rows = [
    {"email": "alice@example.com", "signup_date": "2025-02-01", "age": "29"},
    {"email": "",                 "signup_date": "2025-02-01", "age": "29"},
    {"email": "bob@example.com",  "signup_date": "2024-12-30", "age": "41"},
    {"email": "carol@example.com","signup_date": "2026-01-01", "age": "17"},
]
valid = [r for r in rows if looks_like_a_user(r)]
print(len(valid))

Expected Output

1

Common mistakes

  • Tabs and 4-space mixes look identical in a slim editor — configure your editor to render whitespace.
  • A missing colon after def, if, for, etc. produces a SyntaxError that points to the next line — read the caret carefully.
  • Stray trailing commas in argument lists are legal but easy to miss when diffing.

🚀 Performance & Best Practices

  • PEP 8 recommends 4 spaces per indent level — follow it unless your team has agreed otherwise.
  • Use black or ruff format to remove formatting arguments entirely.
  • Readability beats cleverness: prefer if condition: over ternary x if c else y when the condition is long.

🧪 Try It Yourself

  1. Reformat the example above with ruff format and diff the result.
  2. Convert looks_like_a_user into a single boolean expression via a pandas query and benchmark both.
  3. Add type hints to every function and run mypy --strict.

FAQ: Python Syntax

Common questions about this page.

What is Python Syntax?

Python Syntax is a Python Tutorial lesson that explains python syntax in Python. Learn the basic syntax rules and structure of Python programming. Copy the samples and run them in the Python editor. It is written for beginners who want a clear definition and working examples.

Should I run python syntax examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn python syntax in this Python Tutorial Python lesson (Python Syntax).

How do I use python syntax in Python?

To use python syntax in Python, follow the examples on this StudyGrid page. Copy a snippet, run it in the browser, then Download and run it locally for better learning. Change the values and compare the output.

What is the syntax of python syntax?

This Python Syntax tutorial shows python syntax syntax with short Python examples. Use the code blocks in this lesson for the exact statements, then try them in your editor.

Python Syntax example for beginners

Yes. This page includes a beginner python syntax example you can copy and run. It is designed for searches such as "python syntax for beginners", "python syntax example", and "how to use python syntax".

What are common mistakes with python syntax?

Common python syntax mistakes include wrong syntax, mixing types, and skipping practice. Work through this Python Tutorial chapter in order, run every example, and check the output before moving on.

Why should I learn python syntax?

Python Syntax is used in real Python work. Learning python syntax helps you write clearer programs and continue the Python Tutorial tutorial on StudyGrid.

Is Python Syntax free to learn online?

Yes. You can learn python syntax free on StudyGrid (studygrid.in). This chapter is part of the Python Tutorial path and includes examples, syntax, and next-step links.