Python Syntax Notes

Objectives: Python Syntax Notes

Python Syntax Notes

Python Syntax and Fundamentals

1. Python Syntax

Python syntax is the set of rules that defines how a Python program is written. Python is an interpreted language, which means the Python Interpreter reads your code line by line and executes it directly.

Interpreter Note: Python does not need compilation into machine code. It uses the CPython interpreter (by default) which converts Python code into bytecode and executes it.

Example 1: Print Statement

print("Hello, World!")

Output:

Hello, World!

Explanation: The print() function sends text to the standard output. The interpreter reads this line, converts it into bytecode, and executes it immediately.

Example 2: Running a Python File

C:\Users\YourName> python myfile.py

Explanation: The command python myfile.py tells the Python interpreter to read myfile.py, convert it to bytecode, and execute it line by line.

2. Python Indentation

Indentation refers to spaces at the beginning of a line. Unlike many other languages, Python uses indentation to define blocks of code.

Correct Indentation Example

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

Explanation: The code block after if 5 > 2: is indented to indicate that it belongs to the if statement.

Incorrect Indentation Example (Syntax Error)

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

The interpreter throws a SyntaxError because Python expects an indented block after the if statement.

Multiple Correct Indentation Styles

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

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

Note: You must use consistent indentation within the same block. Mixing spaces and tabs or inconsistent spaces leads to errors.

Interpreter Detail: When Python encounters an indented block, it internally groups these lines into a code object for execution. The interpreter uses this to control the flow of your program.

3. Python Variables

Variables store data values. In Python, you create a variable by assigning a value to it. Python is dynamically typed, which means you do not declare the variable type explicitly.

Example: Variables

x = 5
y = "Hello, World!"

Explanation: x is an integer, y is a string. The interpreter keeps track of variable types internally. Python automatically determines the type during runtime.

Interpreter Insight: The Python interpreter stores variable names in memory and binds them to objects. For example, x = 5 binds the name x to an integer object with value 5.

4. Python Comments

Comments are used to explain code. The interpreter ignores them. Comments start with a #.

Example: Single-line Comment

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

Output:

Hello, World!

Example: Multi-line Comment

"""
This is a multi-line comment
or documentation string (docstring)
"""
Interpreter Note: Multi-line comments (docstrings) can be accessed using the .__doc__ attribute of functions, classes, or modules.

5. Summary of How Python Executes Code

  1. Python reads your source code line by line.
  2. The code is converted into bytecode (an intermediate, low-level platform-independent representation).
  3. The Python Virtual Machine (PVM) executes the bytecode.
  4. Indentation defines blocks. Variables store references to objects.
  5. Comments are ignored during execution.

6. Real-life Example: Combining Concepts

# Program to check if a number is positive or negative
num = 10

if num > 0:
    print("The number is positive")
elif num < 0:
    print("The number is negative")
else:
    print("The number is zero")

Output:

The number is positive

Explanation: The interpreter evaluates each line, checks conditions, and executes the corresponding block based on indentation.

Advanced Insight: Each if, elif, and else block is stored as a separate code object internally, which the Python interpreter calls when the condition is true.
Python Full Notes

Python Programming SUMMARY

1. Python Syntax

Python syntax is the set of rules that defines how a Python program is written and executed. You can run Python code in two main ways:

1. Using Python Command Line (Interactive Mode):
>>> print("Hello, World!")
Hello, World!

This executes immediately line by line. The Python interpreter reads your code, converts it into bytecode, and executes it.

2. Using a Python File:
C:\Users\YourName> python myfile.py

Create a file with a .py extension. The Python interpreter reads the file, compiles it to bytecode, and then executes it.

2. Python Indentation

Indentation refers to the spaces at the beginning of a code line. Unlike other programming languages, Python requires indentation to define blocks of code.

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

The indentation tells Python that this line belongs to the if block. If indentation is missing or inconsistent, Python will raise a SyntaxError.

You can use 1 or more spaces, but all lines in the same block must use the same number of spaces (commonly 4 spaces).

3. Python Variables

Variables are containers for storing data values. Python does not require explicit declaration.

x = 5
y = "Hello, World!"
print(x)
print(y)

Here, x is an integer, y is a string. Python automatically detects the data type.

Python interpreter determines the type of variable at runtime. This is called dynamic typing.

4. Python Comments

Comments are used to explain code and are ignored by the Python interpreter.

# This is a single-line comment
print("Hello, World!")  # This prints a message

Comments help developers understand code logic without affecting execution.

5. How Python Executes Code

  1. Parsing: The interpreter reads your code and checks for syntax errors.
  2. Compilation: Python converts the code into bytecode, an intermediate, low-level representation.
  3. Execution: The Python Virtual Machine (PVM) executes the bytecode line by line.
print("Hello, World!")

1. Parser checks syntax. ✅
2. Code compiled into bytecode.
3. PVM executes bytecode and prints: Hello, World!

6. Real Examples of Python Code

# Conditional statement example
age = 20
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

Python evaluates the condition and executes the proper block of code.

# Loop example
for i in range(5):
    print("Number:", i)

The for loop runs 5 times. Each iteration executes indented code as a block.

7. Key Notes

  • Python uses indentation instead of braces ({}) to define code blocks.
  • Variables are dynamically typed. You do not need to declare type explicitly.
  • Comments are written using #.
  • Python code is interpreted line by line by the Python Virtual Machine (PVM).
  • Code in a .py file is compiled into bytecode before execution.
  • Consistent indentation is required to avoid SyntaxError.

8. Extra Tips for Beginners

  1. Use 4 spaces per indentation for readability.
  2. Always comment your code for clarity.
  3. Use meaningful variable names.
  4. Run small chunks of code to understand behavior.

Reference Book: N/A

Author name: MWALA_LEARN Work email: biasharabora12@gmail.com
#MWALA_LEARN Powered by MwalaJS #https://mwalajs.biasharabora.com
#https://educenter.biasharabora.com

:: 1::