Python Syntax
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Python Syntax

Gocourse

Python Syntax 

As discussed earlier, Python code can be executed in two primary ways.

1. Executing Python in the Command Line (Interactive Mode)

Python allows you to run code directly in the command line using its interactive shell. This is useful for quick testing and learning.
>>> print("Hello, World!") Hello, World!
Here, the Python interpreter executes the statement immediately and displays the output.

2. Executing Python Using a .py File (Script Mode)

You can also write Python code in a file with the .py extension and run it through the command line.

C:\Users\YourName> python myfile.py

This approach is commonly used for building real-world applications and programs.

Python Indentation

Indentation refers to the spaces at the beginning of a line of code.
 Unlike many other programming languages where indentation is only for readability, indentation is mandatory in Python.
Python uses indentation to define blocks of code such as conditions, loops, functions, and classes.


Example 1: Correct Indentation (if condition)

Five is greater than two!

Here, the indented line belongs to the if block, so it executes correctly.

Example 2: Missing Indentation (Syntax Error)

File "/code/49738e76-d199-444e-89a2-c7c66d8af850/code.py", line 2 print("Five is greater than two!") ^ IndentationError: expected an indented block

❌ This will result in a SyntaxError because the block is not indented.

Spaces in Indentation

You can choose how many spaces to use for indentation, but:
The most common standard is 4 spaces
At least one space is required
Consistency is mandatory within the same block


Example 3: Different Valid Indentations

Ten is greater than five Ten is greater than five

Both examples work because the indentation is consistent within each block.


Example 4: Inconsistent Indentation (Syntax Error)

File "/code/e1e09c85-e058-4720-a8cf-dc5635c45e61/code.py", line 3 print("This will cause an error") IndentationError: unexpected indent

❌ Python throws an IndentationError because different indentation levels are used in the same block.

More Programs to Understand Indentation

Example 5: Indentation with for Loop

Hello Python Hello Python Hello Python

Both print statements belong to the loop and will execute three times.

Example 6: Incorrect Loop Indentation

File "/code/98b1352d-19ee-4131-8c49-5c3220fc6a87/code.py", line 2 print("Hello") ^ IndentationError: expected an indented block

❌ This will cause an error due to missing indentation.

Example 7: Indentation in Functions

Welcome to Python Learning is easy

The indented lines define the function body.


Our website uses cookies to enhance your experience. Learn More
Accept !