Python Syntax

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)

Try it Yourself

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

Example 2: Missing Indentation (Syntax Error)

Try it Yourself

❌ 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

Try it Yourself

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

Example 4: Inconsistent Indentation (Syntax Error)

Try it Yourself

❌ 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

Try it Yourself

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

Example 6: Incorrect Loop Indentation

Try it Yourself

❌ This will cause an error due to missing indentation.

Example 7: Indentation in Functions

Try it Yourself

The indented lines define the function body.


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