Intro to Python, the Basics

Intro to Python, the Basics

Intro to Python, the Basics

Step 1 of 9

Project 1: The "Hello World" Program

# =============================================================================
# PROJECT 1: THE "HELLO WORLD" PROGRAM
# This is the most basic program possible.
# Its only job is to display text on your computer screen.
# =============================================================================

# 1. THE COMMAND (print)
# 'print' is a built-in instruction.
# It tells the computer: "Take whatever is inside the parentheses and 
# send it to the output screen (the console or terminal)."
# Note: In Python, 'print' must be lowercase.

# 2. THE CONTAINERS (Parentheses)
# The '(' and ')' brackets are used to hold the data you want the 
# command to use.
# Without these, the computer doesn't know where 
# the instruction starts or ends.

# 3. THE DATA TYPE (Quotation Marks)
# The " " marks tell the computer that the information inside is 
# a 'String'.
# This is the coding term for plain text.
# If you remove the quotes, the computer will try to read 'Hello' 
# as a command, fail to find it, and stop with an error.

# 4. THE MESSAGE (Hello, World!)
# This is the actual text the computer will display.
# You can change this to anything you want, as long as it 
# stays inside the quotes.
print("Hello, World!")

# =============================================================================
# HOW THE COMPUTER READS THIS LINE:
# Step 1: It sees 'print' and prepares to output data.
# Step 2: It looks inside the '(' to find the data.
# Step 3: It sees '"' and knows the following characters are just text.
# Step 4: It reads 'Hello, World!' and ignores any logic; it just treats it as text.
# Step 5: It reaches the '"' and ')' which signals the end of the instruction.
# Step 6: It displays 'Hello, World!' on your screen.
# =============================================================================

Project 2: Storing a Name (Variables)

# =============================================================================
# PROJECT 2: STORING A NAME (VARIABLES)
# This program teaches you how to save a piece of information so the 
# computer can remember it and use it later.
# =============================================================================

# 1. CREATING A VARIABLE
# A 'Variable' is just a name you make up to hold data.
# Here, we create the name 'user_name'. 
# The equals sign (=) tells the computer: "Put the text on the right 
# into the name on the left."
user_name = "Alice"

# 2. USING THE VARIABLE
# Now, instead of typing "Alice" every time, we just use the name 'user_name'.
# The computer looks inside that name and finds the text "Alice".
print(user_name)

# 3. COMBINING TEXT AND VARIABLES
# You can combine plain text with your variable using a comma.
# The computer will print the words in quotes first, then the 
# data stored in the variable.
print("Hello,", user_name)

# 4. CHANGING THE DATA
# You can change what is inside a variable at any time.
# The computer will "forget" the old data and remember the new data.
user_name = "Bob"
print("The name is now:", user_name)
Summary of Plain Terms: * **VARIABLE:** A name for a piece of information (like user_name).
* **ASSIGNMENT (=):** The act of putting data into that name.
* **STRING:** The text inside the quotes (like "Alice").
* **OUTPUT:** What you see on the screen after the program runs.

Project 3: Simple Math (Integers)

# =============================================================================
# PROJECT 3: SIMPLE MATH (INTEGERS)
# This program teaches you how to use the computer as a calculator.
# It also shows why numbers are different from text.
# =============================================================================

# 1. CREATING NUMBER VARIABLES
# When you want the computer to do math, do NOT use quotation marks.
# Without quotes, the computer knows these are 'Integers' (whole numbers).
apple_count = 10
orange_count = 5

# 2. ADDITION (+)
# The plus sign tells the computer to add the two values together.
total_fruit = apple_count + orange_count

print("Total fruit count:")
print(total_fruit)

# 3. SUBTRACTION (-)
# The minus sign tells the computer to take the second value away from the first.
remaining_apples = apple_count - 3

print("Apples left after eating three:")
print(remaining_apples)

# 4. MULTIPLICATION (*)
# In coding, we use the asterisk (*) symbol to multiply numbers.
boxes = 2
total_in_boxes = apple_count * boxes

print("Total apples in two boxes:")
print(total_in_boxes)

# 5. DIVISION (/)
# We use the forward slash (/) to divide numbers.
# Note: Division usually results in a decimal number (called a 'Float').
half_apples = apple_count / 2

print("Half of the apples:")
print(half_apples)

# 6. WHY QUOTES MATTER (THE "5 + 5" TRAP)
# If you put numbers in quotes, the computer treats them as text (Strings).
# It will join the text together instead of doing math.
text_math = "5" + "5"
real_math = 5 + 5

print("Result of '5' + '5' (Text):")
print(text_math)  # This will show '55'

print("Result of 5 + 5 (Math):")
print(real_math)  # This will show '10'

Project 4: Making Decisions (If Statements)

# =============================================================================
# PROJECT 4: MAKING DECISIONS (IF STATEMENTS)
# This program teaches the computer how to ask a "True or False" question.
# Depending on the answer, the computer will run different lines of code.
# =============================================================================

# 1. SETTING UP THE DATA
# We create a variable to hold a score.
player_score = 85

# 2. THE "IF" STATEMENT
# An 'if' statement asks a question.
# The symbol '>' means "Is the number on the left bigger than the number on the right?"
# The colon (:) at the end tells the computer: "The question is over, 
# here are the instructions if the answer is YES."
if player_score > 50:
    # 3. INDENTATION (THE SPACES)
    # Notice the 4 spaces before 'print'.
    # These spaces tell the computer that this line ONLY runs 
    # if the 'if' question was TRUE.
    print("You passed the test!")

# 4. THE "ELSE" STATEMENT
# 'else' handles the "NO" answer.
# It runs only if the 'if' question was FALSE.
else:
    print("You did not pass. Try again!")

# 5. COMPARING TWO THINGS (==)
# To check if two things are EXACTLY the same, we use two equals signs (==).
# One equals sign (=) puts data into a variable.
# Two equals signs (==) asks a question: "Are these equal?"
user_input = "password123"
correct_password = "password123"

if user_input == correct_password:
    print("Access Granted!")
else:
    print("Access Denied!")

# 6. CODE OUTSIDE THE CHOICE
# This line has no spaces at the start.
# This means it is NOT part of the 'if' or 'else' choices.
# It will run no matter what happens above.
print("The program has finished checking.")

Project 5: Repeating Tasks (For Loops)

# =============================================================================
# PROJECT 5: REPEATING TASKS (FOR LOOPS)
# This program teaches you how to automate a task.
# Instead of writing a line five times, you write it once and tell 
# the computer to repeat it for a group of items.
# =============================================================================

# 1. CREATING A LIST
# To use a loop, we first need a group of items.
# A 'List' is created using square brackets [ ].
# Every item in the list is separated by a comma.
fruit_list = ["Apple", "Banana", "Cherry", "Date"]

# 2. THE 'FOR' LOOP
# This line tells the computer: "For every single item inside fruit_list, 
# do the following steps."
# 'single_fruit' is a temporary name we make up to represent the 
# item the computer is currently looking at.
for single_fruit in fruit_list:
    # 3. THE REPEATED ACTION
    # This line is indented (4 spaces).
    # The computer will run this line for "Apple", then "Banana", 
    # then "Cherry", and finally "Date".
    print("Checking item...")
    print("The current fruit is:", single_fruit)

# 4. ENDING THE LOOP
# This line has no spaces.
# The computer will only run this AFTER it has finished 
# going through every item in the list.
print("All fruits have been checked!")

# 5. LOOPING WITH NUMBERS (range)
# If you just want to repeat something a specific number of times, 
# you use 'range'.
# This tells the computer to count from 0 to 4.

print("Counting to five:")
for number in range(5):
    print("Number:", number)

Project 6: Organizing Code (Functions)

# =============================================================================
# PROJECT 6: ORGANIZING CODE (FUNCTIONS)
# A 'Function' is a mini-program inside your script.
# You give a block of code a name, and then you can "call" that name 
# whenever you want the computer to run those specific instructions.
# =============================================================================

# 1. DEFINING A FUNCTION
# Use 'def' (short for define) to start.
# Give it a name (like 'say_hello').
# Use parentheses () and a colon : to finish the setup.
def say_hello():
    # Everything indented here belongs to this function.
    print("The function is now running...")
    print("Hello from inside the function!")

# 2. CALLING A FUNCTION
# Defining the function doesn't run the code yet.
# You must "call" it by typing its name with parentheses.
say_hello()

# 3. FUNCTIONS WITH INPUTS (PARAMETERS)
# You can put a variable name inside the parentheses.
# This allows you to send data into the function.
def greet_user(name):
    print("Hello,", name, "- Welcome to the program!")

# Now we call it and send a specific piece of text into it.
greet_user("Alice")
greet_user("Bob")

# 4. FUNCTIONS WITH MATH (RETURN)
# A function can do work and then "return" the result back to you.
# Think of 'return' as the function's final answer.

def add_numbers(num1, num2):
    answer = num1 + num2
    return answer

# We save the function's "answer" into a new variable.
total = add_numbers(10, 5)
print("The math result is:", total)

Project 7: Importing Modules (External Code)

# =============================================================================
# PROJECT 7: IMPORTING MODULES (EXTERNAL CODE)
# A 'Module' is a file containing code written by other people.
# The 'import' command tells the computer to load one of these files 
# so you can use the instructions inside it.
# =============================================================================

# 1. LOADING THE MODULES
# These commands must usually go at the very top of your script.
import math    # Loads code for advanced math (like square roots).
import random  # Loads code for picking numbers by chance.
import time    # Loads code for handling time and delays.
import os      # Loads code for interacting with the computer's files.

# 2. USING THE MATH MODULE
# To use a command from a module, you type the module name, 
# then a dot (.), then the specific command.
# 'sqrt' stands for Square Root.
number = 16
result = math.sqrt(number)

print("The square root of 16 is:")
print(result)

# 3. USING THE RANDOM MODULE
# 'randint' stands for Random Integer.
# It picks a whole number between the two numbers you provide.
dice_roll = random.randint(1, 6)

print("You rolled a:")
print(dice_roll)

# 4. USING THE TIME MODULE
# 'sleep' tells the computer to stop and wait for a specific 
# number of seconds before moving to the next line.
print("Waiting for 2 seconds...")
time.sleep(2)
print("Done waiting!")

# 5. USING THE OS MODULE
# 'getcwd' stands for Get Current Working Directory.
# It shows you which folder the script is currently running in.
current_folder = os.getcwd()

print("The script is running in this folder:")
print(current_folder)

Project 7.1 & 7.2: Wildcards & Conflicts

# =============================================================================
# PROJECT 7.1: IMPORTING EVERYTHING (THE WILDCARD)
# This program shows how to load every single command from a module 
# at once so you don't have to type the module's name every time.
# =============================================================================

# 1. THE STANDARD WAY (Review)
import math
print(math.sqrt(16)) 

# 2. THE "IMPORT ALL" WAY (The Asterisk)
# This line says: "From the math module, import EVERYTHING (*)."
from math import *

# 3. USING COMMANDS DIRECTLY
print(sqrt(64))
print(pi)

# =============================================================================
# PROJECT 7.2: THE PROBLEM WITH "IMPORT *" (NAME OVERWRITING)
# This program shows why importing everything at once can be risky.
# =============================================================================

# 1. THE SETUP
# Imagine two toolkits have a command called 'calculate'.
# If you import * from both, the second one "overwrites" the first.

# 3. A REAL-WORLD EXAMPLE
# Both 'math' and 'cmath' have a command called 'sqrt'.
from math import *
from cmath import *

# The computer will use the 'cmath' version because it was imported LAST.
result = sqrt(-1) 
print(result)

# 4. THE BETTER WAY (NAMESPACING)
import math
import cmath

print(math.sqrt(16))
print(cmath.sqrt(-1))

Final Project: The Dice Roller

import random

def roll_die(die_type):
    match die_type:
        case 6:
            return random.randint(1, 6)
        case 8:
            return random.randint(1, 8)
        case 10:
            return random.randint(1, 10)
        case 12:
            return random.randint(1, 12)
        case 20:
            return random.randint(1, 20)
        case _:
            return None

print("Available dice: 6, 8, 10, 12, 20")
print("Type x to exit")

while True:
    user_input = input("Which die to roll? d").lower().strip()

    if user_input == 'x':
        print("Exiting.")
        break 

    try:
        selection = int(user_input)
        
        if roll_die(selection) is None:
            print("Invalid die type.")
            continue

        count_input = input("How many do you want to roll? ")
        num_dice = int(count_input)

        if num_dice <= 0:
             print("Quantity must be at least 1.")
             continue

        rolls = []
        for i in range(num_dice):
            rolls.append(roll_die(selection))

        print("Rolling " + str(num_dice) + "d" + str(selection))
        print("Results:", rolls)
        print("Total Sum:", sum(rolls))
        print("-" * 20)

    except ValueError:
        print("Error: Please enter a numeric value.")