Session-2-1-Examples

This page shows the annotated source code for Session-2-1-Examples.py in browser-friendly HTML format. It was generated automatically from the original Python file.

Source File Session-2-1-Examples.py
Folder Chapter-2-Basic-Sessions

import sys
sys.stdout.reconfigure(encoding='utf-8')

"""
Session 1: Python Basics & Setup - Code Examples
Introduction to Python Course
"""

# ============================================
# PART 1: Your First Program
# ============================================
print("=" * 50)
print("PART 1: Hello World")
print("=" * 50)
# ======================================================
# WHAT THIS SECTION DOES:
# 1) PURPOSE: Introduces the simplest Python program -
#    printing text to the screen. Every programmer's
#    first step: making the computer say something!
#
# 2) VS CODE: Select the 2 lines below this comment,
#    then press Shift+Enter to run them in the terminal.
#    You should see "Hello, World!" appear in the output.
# ======================================================

print("Hello, World!")
print("Welcome to Python Programming!")


# ============================================
# PART 2A: Variables and Data Types
# ============================================
print("\n" + "=" * 50)
print("PART 2: Variables and Data Types")
print("=" * 50)
# ======================================================
# WHAT THIS SECTION DOES:
# 1) PURPOSE: Teaches how Python stores information using
#    variables. A variable is like a labeled box that holds
#    a value. Python has several types: text (str), whole
#    numbers (int), decimal numbers (float), and True/False
#    values (bool).
#
# 2) VS CODE: Select all the code under PART 2 (Parts 2A
#    through 2E), then press Shift+Enter. Watch the terminal
#    to see each variable printed with its value and type.
# ======================================================

# ============================================
# PART 2B: String variables
# ============================================
# ======================================================
# WHAT THIS SECTION DOES:
# 1) PURPOSE: Strings store text. Any characters between
#    quotes (single ' or double ") become a string.
#    f-strings (f"...") let you embed variables directly
#    inside printed text using curly braces {}.
#
# 2) VS CODE: Select the 3 lines below, press Shift+Enter.
#    You should see: Name: Alice, City: New York
# ======================================================

# ------------------------------------------------------
# HOW print(f"...") WORKS  --  THE F-STRING EXPLAINED
# ------------------------------------------------------
#
#   A regular print shows only fixed text:
#       print("Hello")         -->  Hello
#
#   An f-string starts with the letter  f  before the
#   opening quote:
#       print(f"Hello")        -->  Hello   (same so far)
#
#   The magic: put a variable name inside  { }  and
#   Python replaces it with the variable's value:
#       name = "Alice"
#       print(f"Hello {name}") -->  Hello Alice
#
#   You can have as many { } placeholders as you need:
#       print(f"Name: {name}, City: {city}")
#                       ^              ^
#                       |              |
#                  replaced        replaced
#                  by value        by value
#                  of name         of city
#
#   RULE: the  f  before the quote activates f-string mode.
#         Every variable you want printed MUST be inside { }.
#         Text outside { } is printed exactly as written.
#
#   Common mistake - forgetting the f:
#       print("Hello {name}")  -->  Hello {name}   <- WRONG
#       print(f"Hello {name}") -->  Hello Alice    <- CORRECT
# ------------------------------------------------------

name = "Alice"
city = "New York"
print(f"Name: {name}, City: {city}")   # {name} -> Alice, {city} -> New York

# ============================================
# PART 2C: Numeric variables
# ============================================
# ======================================================
# WHAT THIS SECTION DOES:
# 1) PURPOSE: Python uses int for whole numbers (25, -3)
#    and float for decimals (5.6). Negative numbers work
#    just like in math - simply put a minus sign in front.
#
# 2) VS CODE: Select the 4 lines below, press Shift+Enter.
#    You should see: Age: 25, Height: 5.6, Temperature: -3
# ======================================================

age = 25
height = 5.6
temperature = -3
print(f"Age: {age}, Height: {height}, Temperature: {temperature}")  # {age}, {height}, {temperature} are replaced by their values

# ============================================
# PART 2D: Boolean variables
# ============================================
# ======================================================
# WHAT THIS SECTION DOES:
# 1) PURPOSE: Booleans are the simplest data type - they
#    can only be True or False (capital T and F matter!).
#    They are used for yes/no decisions in your programs.
#
# 2) VS CODE: Select the 3 lines below, press Shift+Enter.
#    You should see: Is Student: True, Has License: False
# ======================================================

is_student = True
has_license = False
print(f"Is Student: {is_student}, Has License: {has_license}")  # True/False values also work inside { }

# ============================================
# PART 2E: Check data types with type()
# ============================================
# ======================================================
# WHAT THIS SECTION DOES:
# 1) PURPOSE: The built-in type() function reveals what
#    kind of data a variable holds. This is very useful
#    when debugging - you can confirm Python sees your
#    variable the way you expect (str, int, float, bool).
#
# 2) VS CODE: Select the 4 print lines below, press
#    Shift+Enter. Notice how each variable shows a
#    different class: <class 'str'>, <class 'int'>, etc.
# ======================================================

print(f"\nType of name: {type(name)}")
print(f"Type of age: {type(age)}")
print(f"Type of height: {type(height)}")
print(f"Type of is_student: {type(is_student)}")


# ============================================
# PART 3A: Arithmetic Operators
# ============================================
print("\n" + "=" * 50)
print("PART 3: Operators")
print("=" * 50)
# ======================================================
# WHAT THIS SECTION DOES:
# 1) PURPOSE: Operators are the math symbols Python uses
#    to calculate values. Beyond +, -, *, / you also have:
#    //  (floor division: divide and drop the decimal)
#    %   (modulus: the remainder after division)
#    **  (exponentiation: raise to a power, e.g. 10**3=1000)
#
# 2) VS CODE: Select all lines from a=10 down through the
#    last print in PART 3A, then press Shift+Enter.
#    Check each result in the terminal against mental math.
# ======================================================

a = 10
b = 3

print(f"Addition: {a} + {b} = {a + b}")
print(f"Subtraction: {a} - {b} = {a - b}")
print(f"Multiplication: {a} * {b} = {a * b}")
print(f"Division: {a} / {b} = {a / b}")
print(f"Floor Division: {a} // {b} = {a // b}")
print(f"Modulus: {a} % {b} = {a % b}")
print(f"Exponentiation: {a} ** {b} = {a ** b}")

# ============================================
# PART 3B: Comparison Operators & String Operations
# ============================================
# ======================================================
# WHAT THIS SECTION DOES:
# 1) PURPOSE: Comparison operators (==, !=, >, <) compare
#    two values and always return True or False. These are
#    the building blocks of all decisions in code.
#    String + (concatenation) joins text together.
#    String * (repetition) repeats text a given number of times.
#
# 2) VS CODE: Select all lines in PART 3B through the
#    laugh print, then press Shift+Enter. Notice that
#    comparing 10 and 3 gives True/False, not a number.
# ======================================================

print(f"\n{a} == {b}: {a == b}")
print(f"{a} != {b}: {a != b}")
print(f"{a} > {b}: {a > b}")
print(f"{a} < {b}: {a < b}")

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(f"\nString concatenation: {full_name}")

laugh = "Ha" * 3
print(f"String repetition: {laugh}")


# ============================================
# PART 4: Input and Output Examples
# ============================================
print("\n" + "=" * 50)
print("PART 4: Input and Output Examples")
print("=" * 50)
# ======================================================
# WHAT THIS SECTION DOES:
# 1) PURPOSE: input() pauses the program and waits for the
#    user to type something. It ALWAYS returns a string, so
#    use int() or float() to convert it when you need a
#    number. The examples are commented out on purpose -
#    they are meant to be uncommented and tried one at a time.
#
# 2) VS CODE: To try Example 1, remove the # from the two
#    lines under "Example 1", select those 2 lines, and
#    press Shift+Enter. The terminal will prompt you to
#    type your name - type it and press Enter to see the
#    greeting. Re-comment the lines when done, then try
#    Example 2 the same way.
# ======================================================

print("\n--- Example 1: Greeting Program ---")
# user_name = input("What is your name? ")
# print(f"Hello, {user_name}! Nice to meet you!")

print("\n--- Example 2: Age Calculator ---")
# birth_year = int(input("What year were you born? "))
# current_year = 2025
# age = current_year - birth_year
# print(f"You are {age} years old!")

print("\n--- Example 3: Simple Calculator ---")
# num1 = float(input("Enter first number: "))
# num2 = float(input("Enter second number: "))
# sum_result = num1 + num2
# print(f"The sum of {num1} and {num2} is {sum_result}")


# ============================================
# PART 5: Practical Examples
# ============================================
print("\n" + "=" * 50)
print("PART 5: Practical Examples")
print("=" * 50)
# ======================================================
# WHAT THIS SECTION DOES:
# 1) PURPOSE: These four mini-programs show how variables
#    and operators combine to solve real-world problems:
#    geometry (rectangle area), science (temperature units),
#    commerce (shopping bill with tax), and text formatting
#    (three ways to build a product label). This is what
#    actual Python programs look like in daily use.
#
# 2) VS CODE: Run each sub-section (Rectangle, Temperature,
#    Shopping Bill, String Formatting) one at a time by
#    selecting its lines and pressing Shift+Enter. Compare
#    the terminal output to the formulas in the code to
#    build confidence that you understand what each line does.
# ======================================================

print("\n--- Rectangle Area Calculator ---")
length = 5.5
width = 3.2
area = length * width
perimeter = 2 * (length + width)
print(f"Length: {length} units")
print(f"Width: {width} units")
print(f"Area: {area} square units")
print(f"Perimeter: {perimeter} units")

print("\n--- Temperature Converter ---")
celsius = 25
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}C is equal to {fahrenheit}F")

print("\n--- Shopping Bill Calculator ---")
item_price = 29.99
quantity = 3
tax_rate = 0.08  # 8% tax

subtotal = item_price * quantity
tax = subtotal * tax_rate
total = subtotal + tax

print(f"Item Price: ${item_price}")
print(f"Quantity: {quantity}")
print(f"Subtotal: ${subtotal:.2f}")   # :.2f inside {} means: show exactly 2 decimal places
print(f"Tax (8%): ${tax:.2f}")        # e.g. 89.97000... becomes 89.97
print(f"Total: ${total:.2f}")

print("\n--- String Formatting Examples ---")
product = "Laptop"
brand = "TechCorp"
price = 899.99

print("Product: " + product + ", Brand: " + brand)
print("Product: {}, Brand: {}, Price: ${}".format(product, brand, price))
print(f"Product: {product}, Brand: {brand}, Price: ${price:.2f}")


# ============================================
# PART 6: Common Mistakes to Avoid
# ============================================
print("\n" + "=" * 50)
print("PART 6: Common Mistakes")
print("=" * 50)
# ======================================================
# WHAT THIS SECTION DOES:
# 1) PURPOSE: Python beginners hit the same errors over and
#    over. This section shows TWO classic traps:
#    (a) You cannot join a string and a number with + directly
#        - you must convert the number to a string with str().
#    (b) input() always returns a string, so you must wrap it
#        with int() or float() before doing math on it.
#    The broken versions are left as comments so you can
#    uncomment them, see the error, and understand WHY it fails.
#
# 2) VS CODE: First run the working line (str(25)) by selecting
#    it and pressing Shift+Enter - it should print "Age: 25".
#    Then uncomment the broken line above it, select it, and
#    press Shift+Enter to see the TypeError in the terminal.
#    Re-comment it, then read the input() mistake comments to
#    understand that pattern without running it.
# ======================================================

# Mistake 1: Trying to concatenate string and number directly
# print("Age: " + 25)  # <-- Uncomment this to see the TypeError!
print("Age: " + str(25))  # Correct: convert number to string first

# Mistake 2: Forgetting to convert input() to a number
# user_age = input("Enter age: ")  # This returns a string!
# next_year_age = user_age + 1     # Error: can't add string + int
# Correct way:
# user_age = int(input("Enter age: "))
# next_year_age = user_age + 1     # Now this works!

print("\nSession 1 completed successfully!")
print("Remember to practice these concepts!")