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
.pyfile extension. - IDEs (like PyCharm or VS Code) provide debugging, autocompletion, and syntax highlighting to avoid errors.
- A valid Python program starts with
print()orinput(), 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
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).
Verify Installation: Open Command Prompt (Windows) or Terminal (macOS/Linux) and type:
python --versionOutput should show the installed version (e.g.,
Python 3.11.4).Choose an IDE:
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!"
- Create a file
hello.pyand add:# This is a comment (ignored by Python) print("Hello, World!") - 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 (▶️).
- Method 1: Open Terminal, navigate to the file’s folder, and type:
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
- Open Terminal and type:
python - Enter commands directly:
>>> 2 + 3 5 >>> name = "Alice" >>> print(f"Hello, {name}!") Hello, Alice! - Exit with
exit()orCtrl+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
- Case Sensitivity:
Print("Hello")→ Error (Python expects lowercaseprint). - Indentation:
Use 4 spaces (never tabs) for blocks. Example:
if 5 > 2: print("Five is greater than two!") # Correct - Colons (
:): Required afterif,for,while, etc.if True: # Missing colon → Error pass - 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:
eSewa (Government Payments)
- Idea Used: Scripting for automation.
- How: Python scripts validate user transactions, check balances, and generate receipts. For example, a script might:
This ensures no negative payments slip through.def validate_payment(amount): if amount <= 0: raise ValueError("Invalid amount") print(f"Processing payment of Rs. {amount}")
Khalti (Digital Wallet)
- Idea Used: REPL for quick testing.
- How: Developers use Python’s REPL to test API responses during wallet transactions. For instance:
This helps debug issues before deploying full scripts.>>> import requests >>> response = requests.get("https://api.khalti.com/v2/lookup/phone/98XXXXXXXX") >>> print(response.json()) {'status': 'success', 'wallet_balance': 5000}
NTC (Telecom Billing)
- Idea Used: File handling for logs.
- How: Python scripts log call durations and generate monthly bills. Example:
This automates billing reports for millions of users.with open("call_logs.txt", "a") as file: file.write("98XXXXXXXX, 2023-10-01, 300s\n")
7. Common Errors and Debugging
Even simple programs can fail. Learn to read error messages.
Error Types
SyntaxError:
- Cause: Missing colon, incorrect indentation.
- Example:
Fix: Addif True print("Error") # Missing colon:afterif.
NameError:
- Cause: Using a variable before assignment.
- Example:
Fix: Initializeprint(x) # x not definedx = 10first.
IndentationError:
- Cause: Inconsistent spacing.
- Example:
Fix: Use 4 spaces uniformly.if True: print("Wrong") # Mixed tabs/spaces
Debugging Tip:
- Use
print()to trace variable values:x = 10 print(f"x is {x}") # Debug line
8. Best Practices for Beginners
- Naming Conventions:
- Variables:
user_age(snake_case). - Functions:
calculate_total().
- Variables:
- Comments:
- Explain why, not just what:
# Calculate tax rate (13% for Nepal) tax_rate = 0.13
- Explain why, not just what:
- Modularity:
- Break code into small functions:
def greet(name): return f"Hello, {name}!"
- Break code into small functions:
- Version Control:
- Use Git to track changes (even for small scripts).
Exam Tip
This unit tests fundamental concepts, not complex logic. Focus on:
- Installation/IDE Setup:
- Know how to verify Python installation (
python --version). - Recognize IDE features (e.g., syntax highlighting in VS Code).
- Know how to verify Python installation (
- Syntax Rules:
- Memorize: colons (
:), indentation, case sensitivity. - Practice fixing errors in given code snippets.
- Memorize: colons (
- REPL vs. Scripts:
- REPL is for interactive testing; scripts are for reusable code.
- Basic I/O:
- Be able to trace
input()/print()examples step-by-step.
- Be able to trace
- 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
.pyscript."
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
IndentationErrorBased on the TU BIM syllabus for Programming with Python (IT243), unit 1.
Discussion
Loading…