🐍 Python Basics β€” Enhanced Teaching Material (Parts 1–6)

1. Introduction to Python

What is Python?
Python is a high-level, interpreted, and general-purpose programming language designed for readability and simplicity. Created by Guido van Rossum in 1991, it emphasizes code clarity and uses English-like syntax. Unlike compiled languages (like C++), Python code is executed line-by-line by an interpreter, making it ideal for rapid development and prototyping.

Why Learn Python?
βœ… Easy to learn β€” minimal boilerplate code
βœ… Cross-platform β€” runs on Windows, macOS, Linux
βœ… Vast ecosystem β€” over 400,000 packages on PyPI
βœ… Dominates AI/ML (TensorFlow, PyTorch), Data Science (Pandas, NumPy), Web Dev (Django, Flask)
βœ… Used by Google, NASA, Instagram, Netflix, Spotify

Key Features of Python

How Python Executes Code

When you run a Python script:

  1. Source code (.py file) is compiled into bytecode (.pyc files).
  2. Bytecode is executed by the Python Virtual Machine (PVM).
  3. This makes Python faster than pure interpreters but slower than compiled languages like Java or C++.
πŸ’‘ Fun Fact: The name β€œPython” comes from the British comedy group β€œMonty Python,” not the snake!

Real-World Examples

# Script to automate file renaming
import os
for filename in os.listdir("."):
    if filename.endswith(".txt"):
        os.rename(filename, filename.replace("old_", "new_"))
# Simple web server (one line!)
python -m http.server 8000
# Data analysis with pandas (requires pip install pandas)
import pandas as pd
data = pd.read_csv("sales.csv")
print(data.head())

πŸ“ Quiz: Introduction to Python

1. What does it mean that Python is an interpreted language?
Correct Answer: C. Code is executed line-by-line by an interpreter without prior compilation to machine code
Python compiles to bytecode (.pyc), but this is not machine code. The PVM interprets bytecode at runtime.
2. Which of these is NOT a reason Python is popular?
Correct Answer: B. Fast execution speed compared to C++
Python is generally slower than compiled languages like C++. Its strength lies in developer productivity, not raw speed.
3. What is the origin of the name "Python"?
Correct Answer: C. Named after the comedy group Monty Python
Guido van Rossum was a fan of the BBC show "Monty Python's Flying Circus."
4. True or False: Python requires explicit declaration of variable types like int x = 5;
Correct Answer: B. False
Python uses dynamic typing: you write x = 5, and Python infers x is an integer.
5. Which of the following best describes Python’s philosophy?
Correct Answer: C. "There should be one β€” and preferably only one β€” obvious way to do it"
This is from the Zen of Python (import this), emphasizing clarity and simplicity.

2. Installing Python and Setting Up the Environment

To begin programming in Python, you need to install the Python interpreter and choose a suitable development environment.

Installing Python

  1. Go to https://www.python.org/downloads/
  2. Download the latest stable release (e.g., Python 3.12.x)
  3. CRITICAL STEP: On Windows, check the box Add Python to PATH before clicking Install.
    Without this, you cannot run python from the command line.
  4. Verify installation by opening terminal (cmd / PowerShell / Terminal) and typing:
python --version

If you see Python 3.12.x, you’re good!

❌ Common Mistake: If you get ''python' is not recognized', Python wasn't added to PATH. Reinstall and check the box!

Virtual Environments (Best Practice)

Python projects often depend on different versions of libraries. To avoid conflicts, use virtual environments:

# Create a virtual environment
python -m venv myproject_env

# Activate it (Windows)
myproject_env\Scripts\activate

# Activate it (macOS/Linux)
source myproject_env/bin/activate

# Now install packages safely
pip install requests

Deactivate with: deactivate

Choosing an Editor/IDE

Tool Pros Cons
VS Code Free, lightweight, excellent Python extension, IntelliSense, debugger, Jupyter support Requires setup (extensions)
PyCharm Community Full IDE features: refactoring, testing, database tools, built-in terminal Heavy on RAM, slower startup
Jupyter Notebook Perfect for data science, visualizations, step-by-step execution Not ideal for large applications or scripting
IDLE Built-in, no setup needed Minimal features, outdated UI

Running Python Code

Interactive Mode: Type python in terminal β†’ you enter REPL (Read-Eval-Print Loop):

>>> print("Hello!")
Hello!
>>> 2 + 3
5
>>> exit()

Script Mode: Save code in a file (e.g., hello.py):

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

# Run in terminal:
python hello.py
πŸ’‘ Pro Tip: Use python -i script.py to run script AND stay in interactive mode afterward.

Example: Writing Your First Script

Create a file called calculator.py:

# calculator.py
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(f"Sum: {num1 + num2}")
print(f"Product: {num1 * num2}")

Run it:

python calculator.py
Enter first number: 5.5
Enter second number: 3
Sum: 8.5
Product: 16.5

πŸ“ Quiz: Installing Python and Environment Setup

1. What happens if you forget to check "Add Python to PATH" during installation on Windows?
Correct Answer: C. You must use the full path like C:\Python312\python.exe every time
Without PATH, the system doesn’t know where to find the python executable globally.
2. What is the purpose of a virtual environment in Python?
Correct Answer: B. To isolate project dependencies so different projects can use different package versions
Prevents "dependency hell" β€” e.g., Project A needs Django 3.2, Project B needs Django 4.2.
3. How do you activate a virtual environment named "venv" on macOS/Linux?
Correct Answer: B. source venv/bin/activate
On Windows: venv\Scripts\activate. Always use source on Unix systems.
4. What does the command python -m venv myenv do?
Correct Answer: B. Creates a new virtual environment called "myenv"
The -m flag runs a module as a script. venv is a standard library module for creating virtual environments.
5. What is the difference between running python script.py and double-clicking the file in Windows Explorer?
Correct Answer: B. Double-clicking opens a window that closes immediately after execution
To keep it open, add input("Press Enter to exit...") at the end of your script.

3. Python Syntax and Structure

Python’s syntax is intentionally minimalistic and readable. Unlike C, Java, or JavaScript, Python uses indentation instead of braces to define code blocks.

Indentation β€” The Heart of Python

Python uses whitespace (spaces or tabs) to indicate blocks. This enforces clean, readable code.

Correct Example

if x > 10:
    print("x is greater than 10")
    y = x * 2
    print(y)
print("This runs regardless")

Incorrect Example

if x > 10:
print("x is greater than 10")  # ❌ IndentationError: expected an indented block
⚠️ Never mix tabs and spaces! Use 4 spaces per indentation level (PEP 8 standard). Most editors auto-convert tabs to spaces.

Comments

Single-line comments start with #:

# This is a comment
x = 5  # This comment explains the variable

Multi-line strings are often used as docstrings (documentation) for functions, classes, or modules:

"""
This is a multi-line string
used as a docstring.
It does not cause an error,
but it's ignored unless assigned.
"""

Line Continuation

Long lines can be broken using:

# Explicit (avoid if possible)
total = 1 + 2 + 3 + \
        4 + 5 + 6

# Implicit (recommended)
total = (1 + 2 + 3 +
         4 + 5 + 6)

# Also works with lists
fruits = [
    "apple",
    "banana",
    "cherry"
]

Semicolons

Optional in Python. You can write multiple statements on one line using semicolons:

x = 5; y = 10; z = x + y
print(z)  # Output: 15
πŸ’‘ But DON’T do this in real code! It reduces readability. Python encourages one statement per line.

Reserved Keywords

These words have special meaning and cannot be used as variable names:

False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
❌ Don't do this: class = 5 β†’ SyntaxError!

Case Sensitivity

Python is case-sensitive:

name = "Alice"
Name = "Bob"
NAME = "Charlie"

print(name)  # Alice
print(Name)  # Bob
print(NAME)  # Charlie

Whitespace Matters Beyond Indentation

Spaces around operators improve readability:

# Good
result = a + b
if x > 5:

# Avoid (but valid)
result=a+b
if x>5:

Example: Real-World Syntax

# Function definition with proper structure
def calculate_area(length, width):
    """Calculate area of rectangle."""
    area = length * width
    return area

# Call function
area = calculate_area(10, 5)
print(f"Area: {area}")

# Conditional logic
if area > 50:
    print("Large room")
elif area >= 20:
    print("Medium room")
else:
    print("Small room")

πŸ“ Quiz: Python Syntax and Structure

1. What will happen if you write this code?
if x > 5:
print("x is big")
Correct Answer: B. Throws a SyntaxError
Missing indentation causes IndentationError β€” Python expects an indented block after if.
2. Which of the following is a valid way to write a multi-line string in Python?
Correct Answer: B. Using triple quotes: ''' ... '''
Triple quotes create a string literal spanning multiple lines. Often used as docstrings.
3. What is the recommended indentation size in Python according to PEP 8?
Correct Answer: B. 4 spaces
PEP 8, Python’s official style guide, recommends 4 spaces per indentation level.
4. Why is the following code invalid?
class = 10
Correct Answer: B. "class" is a reserved keyword
Reserved keywords (like class, def, return) cannot be used as identifiers.
5. What is the output of this code?
a = 10
A = 20
print(a + A)
Correct Answer: A. 30
Python is case-sensitive. a and A are two different variables: 10 + 20 = 30.

4. Variables and Data Types

In Python, variables are labels that point to objects in memory. You don’t declare types β€” Python infers them dynamically.

Dynamic Typing

x = 5          # x is int
x = "hello"      # Now x is str
x = [1, 2, 3]    # Now x is list
x = None         # Now x is NoneType
πŸ’‘ This flexibility allows rapid coding but can lead to bugs if you accidentally reassign a variable.

Core Built-in Data Types

Type Example Description
int 42, -7, 0 Integers β€” unlimited precision
float 3.14, -0.001, 2.0 Floating-point numbers (double precision)
str "Hello", 'Python', '''multi-line''' Immutable sequences of Unicode characters
bool True, False Boolean values β€” used in logic
None value = None Represents absence of value β€” equivalent to null in other languages

Type Checking

print(type(42))        # 
print(type("Hi"))        # 
print(type(3.14))        # 
print(type(True))        # 
print(type(None))        # 

Variable Naming Rules

valid_name     βœ…
_my_var        βœ…
name123        βœ…
123name        ❌ (starts with digit)
class          ❌ (keyword)
first-name     ❌ (hyphen not allowed)

Type Conversion (Casting)

num_str = "123"
num_int = int(num_str)       # β†’ 123
num_float = float(num_str)   # β†’ 123.0

text = str(456)              # β†’ "456"
boolean = bool(0)            # β†’ False
boolean = bool(1)            # β†’ True
boolean = bool("")           # β†’ False (empty string)
boolean = bool(" ")          # β†’ True (non-empty)
❌ int("abc") β†’ ValueError: invalid literal for int() with base 10

Memory Reference Example

a = 10
b = a        # b points to same object as a
print(id(a)) # Same memory address as id(b)
print(id(b))

a = 20       # Now a points to new object
print(b)     # Still 10 β€” b unchanged

Multiple Assignment

# Simultaneous assignment
x, y, z = 1, 2, 3
print(x, y, z)  # 1 2 3

# Swapping values
a, b = 5, 10
a, b = b, a
print(a, b)     # 10 5

Example: Real-World Usage

# Student grade tracker
name = "Maria"
age = 19
gpa = 3.8
is_enrolled = True
graduation_year = None

print(f"Student: {name}, Age: {age}, GPA: {gpa}")
print(f"Enrolled: {is_enrolled}, Grad Year: {graduation_year}")

# Convert user input
user_input = input("Enter your age: ")
age_as_int = int(user_input)  # Converts string to integer
print(f"You will be {age_as_int + 1} next year.")

πŸ“ Quiz: Variables and Data Types

1. What is the output of this code?
x = "5"
y = 3
print(x + y)
Correct Answer: C. TypeError
You cannot concatenate a string ("5") with an integer (3). Must convert: int(x) + y or x + str(y).
2. Which of the following creates a variable of type NoneType?
Correct Answer: C. x = None
Only None has type NoneType. All others are strings, integers, booleans.
3. What does bool("0") evaluate to?
Correct Answer: B. True
Any non-empty string is truthy, even if it contains "0". Only empty string "" is falsy.
4. What is the result of this code?
a = 10
b = a
a = 20
print(b)
Correct Answer: A. 10
When you assign b = a, b references the same object (10). When you change a to 20, a points to a new object β€” b remains unchanged.
5. Which variable name is INVALID in Python?
Correct Answer: C. 2nd_place
Variable names cannot start with a digit. Valid: second_place, place_2.

5. Operators

Operators perform operations on variables and values. Python supports arithmetic, comparison, logical, assignment, identity, and membership operators.

Arithmetic Operators

Operator Name Example Result
+ Addition 5 + 3 8
- Subtraction 10 - 4 6
* Multiplication 7 * 2 14
/ Division 15 / 3 5.0
// Floor Division 15 // 2 7
% Modulus 17 % 5 2
** Exponentiation 2 ** 3 8

Operator Precedence

Python follows PEMDAS:

  1. Parentheses ()
  2. Exponentiation **
  3. Unary plus/minus +x, -x
  4. Multiplication, division, floor division, modulus * / // %
  5. Addition, subtraction + -
result = 2 + 3 * 4 ** 2
# Step-by-step: 4**2 = 16 β†’ 3*16 = 48 β†’ 2+48 = 50
print(result)  # 50

Comparison Operators

==   Equal
!=   Not equal
>    Greater than
<    Less than
>=   Greater than or equal
<=   Less than or equal
x = 5
y = 10
print(x == y)   # False
print(x != y)   # True
print(x < y)    # True

Logical Operators

andReturns True if both operands are true
orReturns True if at least one operand is true
notNegates the boolean value
age = 18
has_license = True

print(age >= 18 and has_license)      # True
print(age < 18 or has_license)        # True
print(not has_license)                # False

Assignment Operators

x = 10
x += 5   # x = x + 5 β†’ 15
x -= 3   # x = x - 3 β†’ 12
x *= 2   # x = x * 2 β†’ 24
x /= 4   # x = x / 4 β†’ 6.0
x //= 2  # x = x // 2 β†’ 3.0
x %= 2   # x = x % 2 β†’ 1.0

Identity Operators

Check if two variables refer to the same object in memory.

a = [1, 2]
b = a
c = [1, 2]

print(a is b)   # True β€” same object
print(a is c)   # False β€” different objects, even though content is same
print(a == c)   # True β€” content equality
πŸ’‘ Use is only to compare with None: if value is None:

Membership Operators

Check if a value exists in a sequence (list, string, tuple, etc.)

fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)     # True
print("grape" not in fruits) # True

text = "Hello World"
print("World" in text)       # True
print("w" in text)           # False (case-sensitive)

Example: Full Operator Demo

# Calculate BMI
weight_kg = 70
height_m = 1.75
bmi = weight_kg / (height_m ** 2)

print(f"BMI: {bmi:.2f}")

if bmi < 18.5:
    category = "Underweight"
elif bmi < 25:
    category = "Normal"
elif bmi < 30:
    category = "Overweight"
else:
    category = "Obese"

print(f"Category: {category}")

# Check eligibility
is_adult = age >= 18
has_id = True
can_vote = is_adult and has_id
print(f"Can vote: {can_vote}")

πŸ“ Quiz: Operators

1. What is the output of 10 // 3?
Correct Answer: B. 3
Floor division // returns the largest integer less than or equal to the result: 10 Γ· 3 = 3.33 β†’ floor is 3.
2. What does 5 == "5" evaluate to?
Correct Answer: B. False
Although they look similar, 5 is an integer, and "5" is a string. Python does not auto-convert types for ==.
3. What is printed by this code?
x = 3
y = 2
z = x ** y + 1
print(z)
Correct Answer: A. 7
Exponentiation first: 3 ** 2 = 9, then 9 + 1 = 10? Wait β€” correction: 3Β² = 9, +1 = 10? Let me recalculate...
Correct Answer: B. 10
Exponentiation has higher precedence: 3 ** 2 = 9, then 9 + 1 = 10.
4. What is the result of not (True and False)?
Correct Answer: A. True
True and False β†’ False β†’ not False β†’ True.
5. Which expression returns True?
Correct Answer: B. [1,2] == [1,2]
Lists with same content are equal (==), but not the same object (is). String literals may be interned, so A might be True, but it's implementation-dependent. B is reliably True.

6. Input and Output

Input/output (I/O) allows interaction between your program and the user or external data sources.

Output: print() Function

The print() function outputs text to the console.

print("Hello, World!")                      # Basic
print("Age:", 25)                             # Multiple args β†’ space separated
print("Name:", name, "Score:", score, sep="-") # Custom separator
print("First", end=" ")                       # No newline
print("Second")                               # Output: "First Second"

# F-strings (formatted strings) β€” MOST COMMON IN MODERN PYTHON
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
print(f"Pi β‰ˆ {3.14159:.2f}")                  # Format to 2 decimals
print(f"{1000:,}")                            # Comma separator β†’ 1,000

Input: input() Function

Always returns a string. You must convert manually.

name = input("Enter your name: ")           # Returns string
age_str = input("Enter your age: ")
age = int(age_str)                              # Convert to integer

# One-liner version
age = int(input("Enter your age: "))

Common Pitfall: Type Errors

# ❌ Wrong
num1 = input("Number 1: ")  # "5"
num2 = input("Number 2: ")  # "3"
print(num1 + num2)          # Output: "53" β€” string concatenation!

# βœ… Correct
num1 = float(input("Number 1: "))
num2 = float(input("Number 2: "))
print(num1 + num2)          # Output: 8.0

Formatted Output β€” Legacy Methods

# .format()
print("Hello {}, you are {} years old.".format(name, age))

# %-formatting (old style β€” avoid in new code)
print("Hello %s, you are %d years old." % (name, age))

Example: Interactive Calculator

# calculator.py
print("=== Simple Calculator ===")
num1 = float(input("Enter first number: "))
op = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))

if op == "+":
    result = num1 + num2
elif op == "-":
    result = num1 - num2
elif op == "*":
    result = num1 * num2
elif op == "/":
    if num2 == 0:
        print("Error: Cannot divide by zero!")
        exit()
    result = num1 / num2
else:
    print("Invalid operator!")
    exit()

print(f"Result: {result}")

Reading from Files (Advanced Preview)

# Read a text file
with open("data.txt", "r") as f:
    content = f.read()
    print(content)

# Write to a file
with open("output.txt", "w") as f:
    f.write("Hello from Python!\n")
    f.write("This is line 2.\n")

Handling Invalid Input Gracefully

while True:
    try:
        age = int(input("Enter your age: "))
        break
    except ValueError:
        print("❌ Please enter a valid integer.")

print(f"You entered: {age}")
πŸ’‘ Always validate user input. Use try-except to handle conversion errors gracefully.

πŸ“ Quiz: Input and Output

1. What is the output of this code?
print("Hello", "World", sep="---")
Correct Answer: B. Hello---World
The sep parameter defines the separator between arguments. Default is space.
2. What is the data type returned by input()?
Correct Answer: C. str
Regardless of what the user types, input() always returns a string.
3. What will this code print?
x = 5
y = 10
print(f"The sum of {x} and {y} is {x+y}.")
Correct Answer: B. The sum of 5 and 10 is 15.
Inside f-strings, expressions in curly braces are evaluated. So {x+y} becomes 15.
4. What happens if you run this?
number = input("Enter a number: ")
print(number * 3)

And user enters: 4

Correct Answer: B. 444
Since input() returns a string, multiplying a string by 3 repeats it: "4" * 3 = "444".
5. Which is the BEST way to read a number from user input safely?
Correct Answer: D. try: num = int(input()) with exception handling
Always handle potential ValueError when converting strings to numbers to prevent crashes.
Version 2