🚀 What is Python & Data Analysis?

Unit 1 — Set up your environment and write your first Python code. No experience needed!

What is Python?

Python is a programming language — a way to give instructions to a computer. It reads almost like English, which makes it perfect for beginners.

Python is used in: data analysis, machine learning, web development, finance, automation, and much more.

python
# This is Python code — # is a comment, Python ignores it print("Hello, World!") # Show text on screen print(2 + 2) # Math print("Data" * 3) # Repeat text
Output
Hello, World! 4 DataDataData

What is Data Analysis?

Data Analysis means examining data to find useful answers — like "Which product sells the most?" or "What month had the highest revenue?"

Python makes this easy with powerful libraries: Pandas, NumPy, and Matplotlib.

💡 Tip: You don't need to be a math expert. Python does the calculations — you just need to ask the right question.

Why Python for Data?

  • ✅ Free and open source
  • ✅ Used by Google, Netflix, NASA, banks, hospitals
  • ✅ Millions of developers worldwide
  • ✅ Thousands of ready-made libraries
  • ✅ Easiest language to learn and read
🎯 TASK Practice: What is Python & Data Analysis?
Print your name, your city, and the result of multiplying 365 × 24 (hours in a year). Each on a separate line.
Starter code:
python
# Write your 3 print statements here: print(???) print(???) print(???)

🚀 Installing Anaconda

Unit 1 — Set up your environment and write your first Python code. No experience needed!

What is Anaconda?

Anaconda is a Python distribution that comes with 300+ pre-installed data science libraries. It's the easiest way to get started — no manual installation needed.

📝 Note: Anaconda is free for personal use. Download from: anaconda.com/download

Installation Steps

  1. Go to anaconda.com/download
  2. Choose your OS (Windows / Mac / Linux)
  3. Download the installer and run it
  4. Click Next until installation is complete
  5. Open Anaconda Navigator from the Start menu

What's Included?

python
# These come pre-installed with Anaconda: import numpy as np # Fast math import pandas as pd # Data tables import matplotlib.pyplot as plt # Charts import seaborn as sns # Beautiful charts import scipy # Scientific computing import sklearn # Machine learning print("All ready! 🎉")
Output
All ready! 🎉
💡 Tip: After installation, open Anaconda Prompt and type: conda list to see all 300+ installed packages.

Keeping Packages Updated

python
# In Anaconda Prompt / Terminal: conda update --all # Update everything conda install package_name # Install new package pip install package_name # Alternative installer
🎯 TASK Practice: Installing Anaconda
Open Anaconda Prompt and check your Python version. Then open Python and verify pandas is installed by printing its version.
Starter code:
python
# In Anaconda Prompt, type: # python --version # Then in Python: import pandas as pd print("Pandas version:", ???) print("Python is ready!")

🚀 Jupyter Notebook Basics

Unit 1 — Set up your environment and write your first Python code. No experience needed!

What is Jupyter Notebook?

Jupyter Notebook is an interactive coding environment that runs in your browser. You write code in cells and see results instantly below each cell — perfect for data analysis.

How to Open Jupyter

  1. Open Anaconda Navigator
  2. Click Launch under Jupyter Notebook
  3. Your browser opens at localhost:8888
  4. Click New → Python 3 (ipykernel)

Essential Keyboard Shortcuts

python
# ── Inside a cell (Edit Mode) ── Shift + Enter # Run cell, move to next Ctrl + Enter # Run cell, stay Alt + Enter # Run cell, insert new below # ── Outside a cell (Command Mode — press Esc) ── A # Add cell Above B # Add cell Below D D # Delete cell M # Change to Markdown (text) Y # Change to Code Z # Undo H # Show all shortcuts
💡 Tip: Press Esc then H to see all keyboard shortcuts — learning them saves hours!

Cell Types

Code cells — run Python code and show output.
Markdown cells — write formatted text, headings, and notes using simple symbols.

python
# This is a Code cell — it runs Python # Markdown cell example (change cell type with M): # # Big Heading # ## Medium Heading # **bold text** # *italic text* # - bullet point
📝 Note: Save your notebook with Ctrl+S. Jupyter also autosaves every few minutes.
🎯 TASK Practice: Jupyter Notebook Basics
Create a notebook with 4 cells: (1) Code: print your name, (2) Code: calculate 365×24×60 (minutes in a year), (3) Markdown: write a heading '# My First Notebook', (4) Code: print today using datetime.
Starter code:
python
# Cell 1 — print your name print(???) # Cell 2 — minutes in a year print(365 * ??? * ???) # Cell 3 — change to Markdown and write: # # My First Notebook # Cell 4 — today's date from datetime import date print(date.today())

🚀 Your First Python Code

Unit 1 — Set up your environment and write your first Python code. No experience needed!

Hello, World!

python
# The classic first program in every language print("Hello, World!") # Variables and f-strings name = "Ahmed" city = "Cairo" print(f"Hello {name} from {city}!")
Output
Hello, World! Hello Ahmed from Cairo!

Working with Numbers

python
price = 100 quantity = 5 discount = 0.10 total = price * quantity after_discount = total * (1 - discount) print(f"Total: {total}") print(f"Discount: {after_discount}") print(f"You save: {total - after_discount:.2f}")
Output
Total: 500 Discount: 450.0 You save: 50.00

Getting User Input

python
name = input("What is your name? ") age = int(input("How old are you? ")) print(f"Hello {name}!") print(f"In 5 years you will be {age + 5}.")
💡 Tip: Always use int() or float() to convert input to a number — input() always returns text.

Multiple Values in One Print

python
x, y, z = 10, 20, 30 # Assign multiple values print(x, y, z) # Print with spaces print(x, y, z, sep=", ") # Custom separator print(f"{x} + {y} = {x+y}")
Output
10 20 30 10, 20, 30 10 + 20 = 30
🎯 TASK Practice: Your First Python Code
Build a simple invoice calculator: ask for product name, price, and quantity. Print a formatted invoice showing subtotal, 14% VAT, and total.
Starter code:
python
product = input("Product name: ") price = float(input("Price: ")) quantity = int(input("Quantity: ")) subtotal = ??? vat = ??? total = ??? print(f"\n=== Invoice ===") print(f"Product: {product}") print(f"Subtotal: {subtotal}") print(f"VAT 14%: {vat:.2f}") print(f"Total: {total:.2f}")

🚀 Understanding Errors

Unit 1 — Set up your environment and write your first Python code. No experience needed!

Errors Are Normal

Every programmer — beginner to expert — sees errors constantly. The skill is reading the error message to understand what went wrong and fix it quickly.

The 5 Most Common Errors

python
# 1. SyntaxError — wrong format/spelling # print("hello" ← missing bracket # → SyntaxError: unexpected EOF # 2. NameError — variable not defined yet # print(total) ← total was never created # → NameError: name 'total' is not defined # 3. TypeError — wrong type for operation # age = "25" # print(age + 1) ← can't add text + number # → TypeError: can only concatenate str # 4. ZeroDivisionError # print(100 / 0) # → ZeroDivisionError: division by zero # 5. IndexError — index out of range # items = [1, 2, 3] # print(items[5]) ← only 3 items! # → IndexError: list index out of range

How to Read Error Messages

  1. Look at the LAST line — it says WHAT went wrong
  2. Look at the arrow (^) — it shows WHERE
  3. Read the line number — it tells you exactly where
python
# Example: fixing a TypeError salary_text = "5000" # This is TEXT salary = int(salary_text) # Convert to number first bonus = 1000 total = salary + bonus print(f"Total pay: {total:,}")
Output
Total pay: 6,000
💡 Tip: When stuck, copy the full error message and search Google — someone has had the exact same problem before.

try / except — Handle Errors Gracefully

python
try: age = int(input("Enter your age: ")) print(f"You are {age} years old.") except ValueError: print("Please enter a valid number!") except Exception as e: print(f"Something went wrong: {e}")
🎯 TASK Practice: Understanding Errors
The code below has 4 bugs. Find them all and fix them.
Starter code:
python
# Buggy code — find 4 errors: Name = ahmed salary = "8000" bonus = 500 years = 0 annual = salary + bonus avg = annual / years print(f"Hello {name}, annual pay: {annual}, monthly avg: {avg}")

🚀 Variables & Operators

Unit 1 — Set up your environment and write your first Python code. No experience needed!

Variable Naming Rules

python
# ✅ Valid names first_name = "Ahmed" total_sales = 450000 _private = "hidden" salesQ1 = 120000 # ❌ Invalid names # 2fast = True ← can't start with number # my-var = 5 ← hyphens not allowed # class = "A" ← reserved keyword

All Arithmetic Operators

python
a, b = 17, 5 print(a + b) # 22 — addition print(a - b) # 12 — subtraction print(a * b) # 85 — multiplication print(a / b) # 3.4 — division (always float) print(a // b) # 3 — floor division print(a % b) # 2 — modulus (remainder) print(a ** b) # 1419857 — power
Output
22 12 85 3.4 3 2 1419857

Comparison & Logical Operators

python
x = 85 print(x > 80) # True print(x == 100) # False print(x >= 80 and x < 90) # True — both must be True print(x < 60 or x > 80) # True — at least one True print(not x == 100) # True — reverses bool
Output
True False True True True

Assignment Operators

python
sales = 1000 sales += 500 # sales = sales + 500 → 1500 sales -= 200 # sales = sales - 200 → 1300 sales *= 2 # sales = sales * 2 → 2600 sales //= 3 # sales = sales // 3 → 866 print(sales)
Output
866
🎯 TASK Practice: Variables & Operators
Write a program that takes monthly salary and calculates: annual salary, income tax (20% if > 100000 else 15%), and net annual salary after tax.
Starter code:
python
monthly = 9500 annual = ??? tax_rate = ??? if annual > 100000 else ??? tax = ??? net = ??? print(f"Annual: {annual:,}") print(f"Tax rate: {tax_rate:.0%}") print(f"Tax: {tax:,}") print(f"Net: {net:,}")

🚀 Virtual Environments & pip

Unit 1 — Set up your environment and write your first Python code. No experience needed!

What is a Virtual Environment?

A virtual environment is an isolated Python workspace. Each project gets its own packages — no conflicts between projects.

📝 Note: Think of it like separate toolboxes: Project A uses library v1.0, Project B uses v2.0 — they don't interfere.

Creating a Virtual Environment

python
# In Terminal / Anaconda Prompt: # Create environment named "myproject" conda create -n myproject python=3.11 # Activate it conda activate myproject # Windows/Mac/Linux # Deactivate when done conda deactivate

Installing Packages with pip

python
# Install a package pip install pandas # Install specific version pip install pandas==2.1.0 # Install multiple packages at once pip install pandas numpy matplotlib # Upgrade a package pip install --upgrade pandas # Uninstall pip uninstall pandas # See all installed packages pip list # Save project requirements to a file pip freeze > requirements.txt # Install from requirements file (share with team) pip install -r requirements.txt
💡 Tip: Always activate your environment before installing packages. Use conda activate env_name first.

Conda vs pip

python
# conda — better for data science (handles non-Python deps) conda install scikit-learn # pip — universal Python package manager pip install some-package # Check environment info conda info conda list
🎯 TASK Practice: Virtual Environments & pip
Create a new conda environment called 'dataproject', activate it, and install pandas and openpyxl. Then verify they're installed.
Starter code:
python
env_name = "dataproject" packages = ["pandas", "openpyxl"] commands = [ f"conda create -n {env_name} python=3.11", f"conda activate {env_name}", "pip install " + " ".join(packages), "python -c \"import pandas, openpyxl; print('ready')\"" ] print("Run these commands in Anaconda Prompt:") for command in commands: print(command)

🚀 Python in VS Code

Unit 1 — Set up your environment and write your first Python code. No experience needed!

Why VS Code?

VS Code is a free, powerful code editor by Microsoft. Many professionals prefer it over Jupyter for writing larger Python files and projects.

Setup VS Code for Python

  1. Download from code.visualstudio.com
  2. Install the Python extension by Microsoft
  3. Install the Jupyter extension to run notebooks
  4. Press Ctrl+Shift+P → "Select Python Interpreter" → choose your conda env

Essential VS Code Shortcuts

python
# Running code: F5 # Run with debugger Ctrl+F5 # Run without debugger Shift+Enter # Run selected line (Python extension) # Editing: Ctrl+/ # Toggle comment Alt+Up/Down # Move line up/down Ctrl+D # Select next occurrence Ctrl+Shift+K # Delete line # Navigation: Ctrl+P # Quick open file Ctrl+` # Open terminal Ctrl+Shift+P # Command palette (most important!)
💡 Tip: Use Ctrl+Shift+P and type what you want — VS Code has thousands of commands accessible this way.

Running Python Files

python
# Create a file: analysis.py # Add your code: import pandas as pd print("Hello from VS Code!") # Run in terminal: # python analysis.py # Or press the ▶ button in the top right
📝 Note: For data analysis work, Jupyter notebooks are better for exploring. Use .py files for reusable scripts and pipelines.
🎯 TASK Practice: Python in VS Code
In VS Code: create a file called 'hello.py', write a script that prints your name and today's date, then run it from the terminal.
Starter code:
python
# hello.py # Import the date module from datetime import ??? name = "Your Name" today = ???.today() print(f"Hello, {name}!") print(f"Today is: {today}")

🚀 Running Python Scripts

Unit 1 — Set up your environment and write your first Python code. No experience needed!

Ways to Run Python

python
# 1. Interactive Python shell # Open Anaconda Prompt and type: python # >>> print("Hello") # Hello # 2. Run a .py file # python my_script.py # 3. Jupyter Notebook cell (Shift+Enter) # 4. VS Code with Run button (▶) # 5. IPython (enhanced interactive shell) # Type: ipython in Anaconda Prompt

Python Script Structure

python
#!/usr/bin/env python3 """ Sales Analysis Script Author: Ahmed Date: 2024-01 """ # 1. Imports at the top import pandas as pd import matplotlib.pyplot as plt # 2. Constants FILE_PATH = "sales_data.csv" TAX_RATE = 0.14 # 3. Functions def calculate_tax(amount): return amount * TAX_RATE # 4. Main code if __name__ == "__main__": print("Running analysis...") df = pd.read_csv(FILE_PATH) print(f"Loaded {len(df)} rows")
💡 Tip: The if __name__ == "__main__": block runs only when the file is executed directly, not when imported.

Command Line Arguments

python
import sys # Run as: python script.py Ahmed 25 name = sys.argv[1] # First argument age = sys.argv[2] # Second argument print(f"Hello {name}, age {age}")
🎯 TASK Practice: Running Python Scripts
Create a script 'sales_report.py' that: (1) defines a list of 5 monthly sales, (2) calculates total/average/max, (3) prints a formatted report, (4) uses if __name__ == '__main__'.
Starter code:
python
#!/usr/bin/env python3 """Monthly Sales Report""" def analyze_sales(sales): total = ??? average = ??? best = ??? return total, average, best if __name__ == "__main__": monthly_sales = [45000, 52000, 48000, 61000, 72000] total, avg, best = analyze_sales(???) print("=== Sales Report ===") print(f"Total: {total:,}") print(f"Average: {avg:,.0f}") print(f"Best: {best:,}")

🚀 Comments & Code Style

Unit 1 — Set up your environment and write your first Python code. No experience needed!

Why Style Matters

Clean code is easier to read, debug, and share. Python has an official style guide called PEP 8.

Comments

python
# Single line comment — explain WHY not WHAT """ Multi-line docstring Used for functions, classes, and modules """ def calculate_profit(revenue, cost): """ Calculate profit margin as a percentage. Args: revenue (float): Total revenue cost (float): Total cost Returns: float: Profit margin percentage """ return (revenue - cost) / revenue * 100 # ✅ Good comment — explains WHY salary *= 1.15 # 15% raise approved in Q3 review # ❌ Bad comment — states the obvious salary *= 1.15 # multiply salary by 1.15

PEP 8 Key Rules

python
# ✅ Naming conventions my_variable = 10 # snake_case for variables MY_CONSTANT = 3.14 # UPPER_CASE for constants def my_function(): pass # snake_case for functions class MyClass: pass # PascalCase for classes # ✅ Spacing x = 1 + 2 # spaces around operators def func(x, y): # spaces after commas pass # ✅ Line length — max 79 characters # ✅ Two blank lines between top-level functions # ✅ One blank line between methods in a class
💡 Tip: Install autopep8 or black to auto-format your code: pip install black then black myfile.py

Readable Code Example

python
# ❌ Hard to read def calc(r,c,t=0.14): p=(r-c)/r*100;v=r*t;return p,v # ✅ Easy to read def calculate_financials(revenue, cost, vat_rate=0.14): """Calculate profit margin and VAT amount.""" profit_margin = (revenue - cost) / revenue * 100 vat_amount = revenue * vat_rate return profit_margin, vat_amount
🎯 TASK Practice: Comments & Code Style
Rewrite the messy code below following PEP 8 style: proper naming, spacing, comments, and a docstring.
Starter code:
python
# Messy code — clean it up! def c(x,y,z=0.14): a=x*y b=a*z c=a+b return a,b,c R=1000 Q=5 subtotal,vat,total=c(R,Q) print(f"s:{subtotal} v:{vat:.2f} t:{total:.2f}")