Lesson 3: Python Syntax and Execution


Execute Python Syntax

Python syntax can be executed in two primary ways: interactively in the Command Line or by creating and running Python files.

1. Interactive Command Line

In the interactive mode, you can directly write and execute Python code in the Command Line. For example:

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

Hello, World!

2. Python Files

You can also create Python files with the .py extension and run them in the Command Line. Here's an example:

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

Python Indentation

Indentation is a crucial aspect of Python syntax, and it refers to the spaces at the beginning of a code line. Unlike many other programming languages where indentation is for readability only, Python uses indentation to indicate a block of code.

Example:

if 5 > 2:

    print("Five is greater than two!")

Python will raise an error if indentation is skipped:

Example (Incorrect):

if 5 > 2:

print("Five is greater than two!")

The number of spaces for indentation is up to the programmer. While four spaces are common, at least one space is required. Consistency is key within the same block of code.

Examples:

if 5 > 2:

    print("Five is greater than two!")

 

if 5 > 2:

        print("Five is greater than two!")

However, inconsistent indentation within the same block will result in a syntax error:

Example (Incorrect):

if 5 > 2:

    print("Five is greater than two!")

        print("Five is greater than two!")

Python Variables

Variables in Python are created when a value is assigned to them. Unlike some languages, Python does not require a specific command for declaring variables.

Example:

x = 5

y = "Hello, World!"

In the Python Variables chapter, you will learn more about working with variables.

Comments

Python supports commenting to provide in-code documentation. Comments begin with a #, and the rest of the line is treated as a comment.

Example:

# This is a comment.

print("Hello, World!")

Comments are useful for explaining code or temporarily disabling specific lines during testing.


Exercises

  1. Interactive Mode: Open the Python interactive shell and execute a simple print statement.
  2. File Execution: Create a Python file (e.g., my_script.py) with a print statement and run it from the Command Line.
  3. Indentation Practice: Write a simple if statement with proper indentation. Experiment with different indentation levels and observe the results.
  4. Variable Assignment: Declare variables of different types (integer, string, etc.) and print their values.
  5. Commenting: Add comments to your code from exercise 4 to explain the purpose of each variable.

These exercises will help reinforce your understanding of Python syntax and its various elements.

 

Post a Comment

0 Comments