Friday, October 17, 2025

How to Write Your First Code in Python

Hey! Based on our Python intro, writing your first code is super straightforward. We'll stick with the classic "Hello, World!" program—it's simple, effective, and a rite of passage for every programmer. I'll walk you through it step by step, including how to create, run, and tweak it.Step 1: Set Up Your EnvironmentIf you haven't already:
  • Download and install Python from python.org (get version 3.12 or later).
  • Open a text editor: Use Notepad (Windows), TextEdit (Mac), or better yet, install VS Code—it's free and beginner-friendly.
  • Or, skip installation: Use an online editor like Replit or Python's official online shell.
Step 2: Write the CodeCreate a new file and save it as hello.py (the .py extension tells your computer it's Python code).Type this in:
python
print("Hello, World!")
  • What's happening? print() is a built-in function that outputs text to the screen. The stuff in quotes is a string—your message.
That's it! One line of code.Step 3: Run the Code
  • In Terminal/Command Prompt:
    1. Open your terminal (search for "cmd" on Windows, "Terminal" on Mac/Linux).
    2. Navigate to where you saved hello.py (e.g., cd Desktop if it's on your desktop).
    3. Type: python hello.py (or python3 hello.py on some systems).
    4. Hit Enter. Boom! Output: Hello, World!
  • In an IDE like VS Code:
    1. Open the file.
    2. Right-click and select "Run Python File in Terminal" (or press Ctrl+F5).
  • Online: Just paste the code and click "Run."
If you see an error like "Python not found," double-check your installation and PATH setup (Google "add Python to PATH" for your OS).Step 4: Make It Yours (Personalize It)Let's level up a bit. Add a variable for your name:
python
name = "Your Name Here"  # Replace with your actual name
print("Hello, World! My name is " + name + ".")
  • Run it again. Output: Hello, World! My name is Your Name Here.
  • Pro tip: Use f-strings for cleaner code (Python 3.6+):
    python
    name = "Your Name Here"
    print(f"Hello, World! My name is {name}.")
Common Gotchas for Beginners
  • Indentation matters: Python uses spaces (not tabs) for structure—don't mix them.
  • Case-sensitive: Print won't work; it's print.
  • Quotes: Use single (') or double (") consistently for strings.
  • Errors? Read them—they're helpful! E.g., SyntaxError means a typo.
What's Next?
  • Try adding math: print(2 + 2)4.
  • Experiment: Change the message, add more print() lines.
  • Challenge: Write code that asks for your age and prints "I'm X years old."
Congrats—you just wrote and ran your first program! 

Lecture Notes: Optimising Numerical Code

Lecture Notes: Optimising Numerical Code Prerequisites: Basic Python programming Understanding of NumPy arrays and vector ...