Programming with PythonUnit 19 min read

Python Basics: Syntax, IDEs, Hello World, and Program Structure

Unit 1 of Programming with Python introduces Python’s core concepts: writing scripts, using an IDE, understanding syntax rules, and structuring simple programs with comments, variables, and basic I/O. This note covers installation, first programs, and the anatomy of a Python script—essential for all later units.

TAKEAWAYS:

  • Python scripts run line-by-line in an interpreter (not compiled), requiring proper indentation and .py file extension.
  • IDEs (like PyCharm or VS Code) provide debugging, autocompletion, and syntax highlighting to avoid errors.
  • A valid Python program starts with print() or input(), and uses # for single-line comments.
  • Syntax errors (e.g., missing colons, wrong indentation) must be fixed before execution.
  • The REPL (interactive shell) is ideal for quick testing, while scripts are saved for reusable code.
  • Python’s case sensitivity and strict whitespace rules distinguish it from languages like C++ or Java.

1. What is Python?

Python is a high-level, interpreted programming language designed for readability and simplicity. Unlike compiled languages (e.g., C++), Python code is executed line-by-line by an interpreter, making debugging easier but slightly slower.

Why Python?

  • Easy to learn: Clean syntax (e.g., print("Hello") vs. System.out.println("Hello") in Java).
  • Versatile: Used in web dev (Django), data science (Pandas), automation, and AI (TensorFlow).
  • Cross-platform: Runs on Windows, macOS, and Linux without modification.

Python vs. Other Languages

Feature Python Java C++
Execution Interpreted Compiled (JVM) Compiled
Syntax Indentation-based Braces {} Braces {}
Typing Dynamic Static Static
Speed Slower Faster Fastest

2. Installing Python and Setting Up an IDE

Before writing code, install Python and an Integrated Development Environment (IDE).

Step-by-Step Installation

  1. Download Python:

    • Visit python.org/downloads and install the latest version (e.g., Python 3.11).
    • Check "Add Python to PATH" during installation (critical for running Python from the command line).
  2. Verify Installation: Open Command Prompt (Windows) or Terminal (macOS/Linux) and type:

    python --version
    

    Output should show the installed version (e.g., Python 3.11.4).

  3. Choose an IDE:

    • Beginner-friendly: Thonny (simple, built-in Python interpreter).
    • Advanced: VS Code (lightweight, extensions like Pylance for autocompletion).
    • Professional: PyCharm (full-featured, paid but free Community Edition).

3. Writing Your First Python Program

A Python program is a script saved with a .py extension. The simplest program prints text to the screen.

Example: "Hello, World!"

  1. Create a file hello.py and add:
    # This is a comment (ignored by Python)
    print("Hello, World!")
    
  2. Run it:
    • Method 1: Open Terminal, navigate to the file’s folder, and type:
      python hello.py
      
    • Method 2: In VS Code/PyCharm, click the Run button (▶️).

Output:

Hello, World!

Key Observations

  • # starts a comment (excluded during execution).
  • print() is a function that outputs text.
  • Indentation matters: Python uses spaces (not braces) to define blocks.

4. The REPL: Python’s Interactive Shell

The REPL (Read-Eval-Print Loop) is Python’s interactive mode—ideal for quick calculations or testing snippets.

How to Use REPL

  1. Open Terminal and type:
    python
    
  2. Enter commands directly:
    >>> 2 + 3
    5
    >>> name = "Alice"
    >>> print(f"Hello, {name}!")
    Hello, Alice!
    
  3. Exit with exit() or Ctrl+Z (Windows) / Ctrl+D (macOS/Linux).

Why Use REPL?

  • Test logic before writing full scripts.
  • Debug errors instantly (e.g., syntax mistakes).

5. Program Structure and Syntax Rules

Python programs follow strict syntax (grammar) rules. Violations cause errors.

Common Syntax Rules

  1. Case Sensitivity: Print("Hello") → Error (Python expects lowercase print).
  2. Indentation: Use 4 spaces (never tabs) for blocks. Example:
    if 5 > 2:
        print("Five is greater than two!")  # Correct
    
  3. Colons (:): Required after if, for, while, etc.
    if True:  # Missing colon → Error
        pass
    
  4. Quotes: Strings can use ' or " (but be consistent).
    print('Single quotes')  # Valid
    print("Double quotes")  # Valid
    

Example: Syntax Error

print("Hello  # Missing closing quote → Error

Error Message:

SyntaxError: EOL while scanning string literal

6. Basic Input/Output (I/O)

Python interacts with users via print() (output) and input() (input).

Example: User Greeting

name = input("Enter your name: ")
print(f"Hello, {name}!")

Trace:

Step Code Executed Output/Input
1 name = input(...) User types "Alice"
2 print(f"Hello, {name}!") Hello, Alice!
flowchart TD
    A["Start"] --> B["input()\nWaits for user"] --> C["Store in variable"] --> D["print()\nDisplays output"] --> E["End"]

In the Real World

Python’s simplicity powers Nepal’s digital ecosystem. Here’s how:

  1. eSewa (Government Payments)

    • Idea Used: Scripting for automation.
    • How: Python scripts validate user transactions, check balances, and generate receipts. For example, a script might:
      def validate_payment(amount):
          if amount <= 0:
              raise ValueError("Invalid amount")
          print(f"Processing payment of Rs. {amount}")
      
      This ensures no negative payments slip through.
  2. Khalti (Digital Wallet)

    • Idea Used: REPL for quick testing.
    • How: Developers use Python’s REPL to test API responses during wallet transactions. For instance:
      >>> import requests
      >>> response = requests.get("https://api.khalti.com/v2/lookup/phone/98XXXXXXXX")
      >>> print(response.json())
      {'status': 'success', 'wallet_balance': 5000}
      
      This helps debug issues before deploying full scripts.
  3. NTC (Telecom Billing)

    • Idea Used: File handling for logs.
    • How: Python scripts log call durations and generate monthly bills. Example:
      with open("call_logs.txt", "a") as file:
          file.write("98XXXXXXXX, 2023-10-01, 300s\n")
      
      This automates billing reports for millions of users.

7. Common Errors and Debugging

Even simple programs can fail. Learn to read error messages.

Error Types

  1. SyntaxError:

    • Cause: Missing colon, incorrect indentation.
    • Example:
      if True
          print("Error")  # Missing colon
      
      Fix: Add : after if.
  2. NameError:

    • Cause: Using a variable before assignment.
    • Example:
      print(x)  # x not defined
      
      Fix: Initialize x = 10 first.
  3. IndentationError:

    • Cause: Inconsistent spacing.
    • Example:
      if True:
      print("Wrong")  # Mixed tabs/spaces
      
      Fix: Use 4 spaces uniformly.

Debugging Tip:

  • Use print() to trace variable values:
    x = 10
    print(f"x is {x}")  # Debug line
    

8. Best Practices for Beginners

  1. Naming Conventions:
    • Variables: user_age (snake_case).
    • Functions: calculate_total().
  2. Comments:
    • Explain why, not just what:
      # Calculate tax rate (13% for Nepal)
      tax_rate = 0.13
      
  3. Modularity:
    • Break code into small functions:
      def greet(name):
          return f"Hello, {name}!"
      
  4. Version Control:
    • Use Git to track changes (even for small scripts).

Exam Tip

This unit tests fundamental concepts, not complex logic. Focus on:

  1. Installation/IDE Setup:
    • Know how to verify Python installation (python --version).
    • Recognize IDE features (e.g., syntax highlighting in VS Code).
  2. Syntax Rules:
    • Memorize: colons (:), indentation, case sensitivity.
    • Practice fixing errors in given code snippets.
  3. REPL vs. Scripts:
    • REPL is for interactive testing; scripts are for reusable code.
  4. Basic I/O:
    • Be able to trace input()/print() examples step-by-step.
  5. Error Messages:
    • Match error types (SyntaxError, NameError) to common mistakes.

Common Exam Questions:

  • "Write a Python script to print your name and age."
  • "Debug the following code (with a syntax error)."
  • "Explain the difference between REPL and a .py script."

Visual Summary:

mindmap
  root((Python Basics))
    Install
      python.org
      PATH
      IDEs (Thonny, VS Code)
    Syntax
      Indentation
      Colons
      Case Sensitivity
    REPL
      Interactive
      Quick Testing
    I/O
      print()
      input()
    Errors
      SyntaxError
      NameError
      IndentationError

Based on the TU BIM syllabus for Programming with Python (IT243), unit 1.

Discussion

Loading…