diff --git a/01_variables.py b/01_variables.py new file mode 100644 index 0000000..eb6a8b9 --- /dev/null +++ b/01_variables.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +""" +01_variables.py + +This file demonstrates the four basic data types in Python: +- int (integers/whole numbers) +- float (floating-point/decimal numbers) +- string (text) +- bool (boolean - True or False) + +Variables are like containers that store information. +You can create a variable by giving it a name and assigning it a value using = +""" + +# ============================================================================ +# INTEGER (int) - Whole numbers without decimal points +# ============================================================================ + +# Create an integer variable called 'age' +age = 25 +print("Age:", age) # Output: Age: 25 +print("Type of age:", type(age)) # type() tells us what kind of data it is + +# Integers can be positive, negative, or zero +score = 100 +temperature = -5 +zero = 0 + +print("\nInteger examples:") +print("Score:", score) +print("Temperature:", temperature) +print("Zero:", zero) + +# You can do math with integers +sum_result = 10 + 5 # Addition +difference = 10 - 3 # Subtraction +product = 4 * 7 # Multiplication +quotient = 20 // 4 # Integer division (gives whole number result) + +print("\nMath with integers:") +print("10 + 5 =", sum_result) +print("10 - 3 =", difference) +print("4 * 7 =", product) +print("20 // 4 =", quotient) + + +# ============================================================================ +# FLOAT (float) - Numbers with decimal points +# ============================================================================ + +# Create a float variable called 'pi' +pi = 3.14159 +print("\n\nPi:", pi) +print("Type of pi:", type(pi)) + +# Floats are used when you need precision with decimals +height = 5.9 # Height in feet +price = 19.99 # Price in dollars +temperature_celsius = 36.6 # Body temperature + +print("\nFloat examples:") +print("Height:", height, "feet") +print("Price: $", price) +print("Temperature:", temperature_celsius, "°C") + +# Math with floats +result1 = 10.5 + 2.3 # Addition with floats +result2 = 7.5 - 1.2 # Subtraction with floats +result3 = 3.0 * 2.5 # Multiplication with floats +result4 = 9.0 / 2.0 # Division with floats (always gives float result) + +print("\nMath with floats:") +print("10.5 + 2.3 =", result1) +print("7.5 - 1.2 =", result2) +print("3.0 * 2.5 =", result3) +print("9.0 / 2.0 =", result4) + + +# ============================================================================ +# STRING (str) - Text data enclosed in quotes +# ============================================================================ + +# Create a string variable called 'name' +# You can use single quotes ' ' or double quotes " " +name = "Alice" +print("\n\nName:", name) +print("Type of name:", type(name)) + +# Strings can contain letters, numbers, spaces, and special characters +greeting = "Hello, World!" +address = '123 Main Street' +message = "I am learning Python!" + +print("\nString examples:") +print(greeting) +print("Address:", address) +print(message) + +# You can combine (concatenate) strings with + +first_name = "John" +last_name = "Doe" +full_name = first_name + " " + last_name # Notice the space in the middle +print("\nCombining strings:") +print("Full name:", full_name) + +# You can repeat strings with * +laugh = "Ha" * 3 # Repeats "Ha" three times +print("Laugh:", laugh) # Output: HaHaHa + +# Strings have many useful methods (functions that work on strings) +sentence = "python is awesome" +print("\nString methods:") +print("Original:", sentence) +print("Uppercase:", sentence.upper()) # Converts to UPPERCASE +print("Capitalized:", sentence.capitalize()) # Capitalizes first letter +print("Length:", len(sentence)) # len() gives the number of characters + + +# ============================================================================ +# BOOLEAN (bool) - True or False values +# ============================================================================ + +# Create boolean variables +is_student = True +is_raining = False +print("\n\nIs student:", is_student) +print("Is raining:", is_raining) +print("Type of is_student:", type(is_student)) + +# Booleans are often the result of comparisons +is_greater = 10 > 5 # Is 10 greater than 5? True +is_equal = 7 == 7 # Is 7 equal to 7? True +is_less = 3 < 2 # Is 3 less than 2? False + +print("\nBoolean comparisons:") +print("10 > 5:", is_greater) +print("7 == 7:", is_equal) +print("3 < 2:", is_less) + +# More comparison operators: +print("\nMore comparisons:") +print("5 != 3:", 5 != 3) # != means "not equal to" +print("8 >= 8:", 8 >= 8) # >= means "greater than or equal to" +print("4 <= 2:", 4 <= 2) # <= means "less than or equal to" + +# You can use logical operators: and, or, not +has_ticket = True +has_id = True +can_enter = has_ticket and has_id # Both must be True + +print("\nLogical operators:") +print("Has ticket:", has_ticket) +print("Has ID:", has_id) +print("Can enter (needs both):", can_enter) + +is_weekend = False +is_holiday = True +can_sleep_in = is_weekend or is_holiday # At least one must be True + +print("Is weekend:", is_weekend) +print("Is holiday:", is_holiday) +print("Can sleep in (needs one):", can_sleep_in) + +is_awake = False +is_asleep = not is_awake # not flips True to False and vice versa + +print("Is awake:", is_awake) +print("Is asleep (opposite of awake):", is_asleep) + + +# ============================================================================ +# VARIABLE NAMING RULES AND BEST PRACTICES +# ============================================================================ + +print("\n\n=== Variable Naming Tips ===") +print("✓ Use descriptive names: 'student_age' instead of 'x'") +print("✓ Use lowercase with underscores: 'first_name' not 'firstName'") +print("✓ Start with letter or underscore: 'name' or '_value'") +print("✗ Don't start with numbers: '1name' is invalid") +print("✗ Don't use Python keywords: 'if', 'for', 'while', etc.") +print("✗ Don't use spaces: 'my name' is invalid, use 'my_name'") + + +# ============================================================================ +# SUMMARY +# ============================================================================ + +print("\n\n=== SUMMARY ===") +print("int: Whole numbers (no decimals)") +print("float: Numbers with decimals") +print("string: Text enclosed in quotes") +print("bool: True or False values") +print("\nYou can check any variable's type using type(variable_name)") +print("Variables can be reassigned to new values at any time!") diff --git a/02_control_flow.py b/02_control_flow.py new file mode 100644 index 0000000..c59e9dd --- /dev/null +++ b/02_control_flow.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +""" +02_control_flow.py + +This file demonstrates control flow in Python: +- if/else statements (making decisions) +- for loops (repeating actions a specific number of times) +- while loops (repeating actions while a condition is true) + +Control flow allows your program to make decisions and repeat actions. +""" + +# ============================================================================ +# IF/ELSE STATEMENTS - Making decisions in code +# ============================================================================ + +print("=== IF/ELSE STATEMENTS ===\n") + +# Simple if statement +# This checks a condition and runs code only if the condition is True +age = 18 + +if age >= 18: + print("You are an adult.") # This runs because 18 >= 18 is True + print("You can vote!") + +print() # Empty line for spacing + +# if/else statement +# This runs one block of code if True, another if False +temperature = 75 + +if temperature > 80: + print("It's hot outside!") +else: + print("It's not too hot.") # This runs because 75 is not > 80 + +print() + +# if/elif/else statement +# elif means "else if" - check multiple conditions +score = 85 + +if score >= 90: + print("Grade: A") +elif score >= 80: + print("Grade: B") # This runs because score is 85 (>= 80 but < 90) +elif score >= 70: + print("Grade: C") +elif score >= 60: + print("Grade: D") +else: + print("Grade: F") + +print() + +# You can combine conditions with 'and' and 'or' +has_ticket = True +has_id = True + +if has_ticket and has_id: + print("Welcome! You can enter.") # Both conditions must be True +else: + print("Sorry, you cannot enter.") + +print() + +# Example with 'or' - at least one condition must be True +is_weekend = False +is_holiday = True + +if is_weekend or is_holiday: + print("Yay! No work today!") # This runs because is_holiday is True +else: + print("Time to go to work!") + +print() + +# Nested if statements (if inside another if) +is_raining = True +has_umbrella = True + +if is_raining: + print("It's raining.") + if has_umbrella: + print("Good thing you have an umbrella!") # This runs + else: + print("You'll get wet!") +else: + print("It's not raining.") + +print("\n") + + +# ============================================================================ +# FOR LOOPS - Repeating actions a specific number of times +# ============================================================================ + +print("=== FOR LOOPS ===\n") + +# Basic for loop - repeat 5 times +# range(5) creates numbers from 0 to 4 (5 numbers total) +print("Counting from 0 to 4:") +for i in range(5): + print("Count:", i) + +print() + +# range() with start and end +# range(1, 6) creates numbers from 1 to 5 (stops before 6) +print("Counting from 1 to 5:") +for i in range(1, 6): + print(i) + +print() + +# range() with start, end, and step +# range(0, 11, 2) creates numbers from 0 to 10, counting by 2 +print("Even numbers from 0 to 10:") +for num in range(0, 11, 2): + print(num) + +print() + +# Loop through a list of items +fruits = ["apple", "banana", "orange", "grape"] +print("My favorite fruits:") +for fruit in fruits: + print("- " + fruit) + +print() + +# Loop through a string (strings are sequences of characters) +word = "Python" +print("Letters in 'Python':") +for letter in word: + print(letter) + +print() + +# Using enumerate() to get both index and value +colors = ["red", "green", "blue"] +print("Colors with their positions:") +for index, color in enumerate(colors): + print(f"Position {index}: {color}") + # Note: f"..." is an f-string, a way to insert variables into strings + +print() + +# Nested loops (loop inside another loop) +print("Multiplication table (1-3):") +for i in range(1, 4): + for j in range(1, 4): + result = i * j + print(f"{i} × {j} = {result}") + print() # Empty line after each number's table + +print() + + +# ============================================================================ +# WHILE LOOPS - Repeating while a condition is true +# ============================================================================ + +print("=== WHILE LOOPS ===\n") + +# Basic while loop +# Keeps running as long as the condition is True +count = 1 +print("Counting up to 5:") +while count <= 5: + print("Count:", count) + count += 1 # Increment count by 1 (same as count = count + 1) + # IMPORTANT: You must change the variable, or the loop runs forever! + +print() + +# Counting down +countdown = 5 +print("Countdown:") +while countdown > 0: + print(countdown) + countdown -= 1 # Decrement by 1 (same as countdown = countdown - 1) +print("Blast off! 🚀") + +print() + +# While loop with user input simulation +# In real programs, you might get input from the user +password = "" +attempts = 0 +correct_password = "python123" + +# Simulate trying to enter password (in real code, you'd use input()) +attempts_data = ["wrong1", "wrong2", "python123"] # Pretend user inputs + +print("Password entry simulation:") +for attempt_input in attempts_data: + attempts += 1 + password = attempt_input + print(f"Attempt {attempts}: Trying password '{password}'") + + if password == correct_password: + print("Access granted! ✓") + break # 'break' exits the loop immediately + else: + print("Incorrect password. Try again.") + +print() + +# Using 'continue' to skip to the next iteration +print("Printing odd numbers from 1 to 10 (using continue):") +num = 0 +while num < 10: + num += 1 + if num % 2 == 0: # If number is even (divisible by 2) + continue # Skip the rest and go to next iteration + print(num) # This only runs for odd numbers + +print() + +# While loop with a flag variable +print("Finding a specific number:") +numbers = [3, 7, 12, 19, 24, 31] +target = 19 +found = False +index = 0 + +while index < len(numbers) and not found: + if numbers[index] == target: + print(f"Found {target} at position {index}!") + found = True + else: + print(f"Position {index}: {numbers[index]} (not the target)") + index += 1 + +if not found: + print(f"{target} not found in the list.") + +print("\n") + + +# ============================================================================ +# CONTROL FLOW BEST PRACTICES +# ============================================================================ + +print("=== CONTROL FLOW TIPS ===") +print("✓ Use if/elif/else for making decisions based on conditions") +print("✓ Use for loops when you know how many times to repeat") +print("✓ Use while loops when you repeat until a condition changes") +print("✓ Always ensure while loops have a way to end (avoid infinite loops)") +print("✓ Use 'break' to exit a loop early") +print("✓ Use 'continue' to skip to the next iteration") +print("✓ Indent your code properly - Python requires correct indentation!") + + +# ============================================================================ +# SUMMARY +# ============================================================================ + +print("\n=== SUMMARY ===") +print("if/else: Make decisions - run different code based on conditions") +print("for loop: Repeat code a specific number of times or for each item") +print("while loop: Repeat code as long as a condition is True") +print("break: Exit a loop immediately") +print("continue: Skip to the next iteration of a loop") +print("\nControl flow makes your programs smart and flexible!") diff --git a/03_functions.py b/03_functions.py new file mode 100644 index 0000000..fefafb2 --- /dev/null +++ b/03_functions.py @@ -0,0 +1,339 @@ +#!/usr/bin/env python3 +""" +03_functions.py + +This file demonstrates functions in Python: +- Defining functions +- Function parameters/arguments +- Return values +- Why functions are useful + +Functions are reusable blocks of code that perform specific tasks. +Think of them as mini-programs within your program! +""" + +# ============================================================================ +# BASIC FUNCTIONS - No parameters, no return value +# ============================================================================ + +print("=== BASIC FUNCTIONS ===\n") + +# Define a simple function using 'def' keyword +# This function just prints a greeting +def greet(): + """This is a docstring - it describes what the function does.""" + print("Hello! Welcome to Python functions!") + +# Call (use) the function by writing its name with () +greet() # Output: Hello! Welcome to Python functions! + +print() + +# Another simple function +def say_goodbye(): + """Prints a goodbye message.""" + print("Goodbye!") + print("Thanks for learning functions!") + +say_goodbye() # Calls the function + +print("\n") + + +# ============================================================================ +# FUNCTIONS WITH PARAMETERS - Accept input +# ============================================================================ + +print("=== FUNCTIONS WITH PARAMETERS ===\n") + +# Function with one parameter +# Parameters are variables that receive values when the function is called +def greet_person(name): + """Greets a person by name.""" + print(f"Hello, {name}! Nice to meet you!") + +# Call the function with different arguments +greet_person("Alice") # Output: Hello, Alice! Nice to meet you! +greet_person("Bob") # Output: Hello, Bob! Nice to meet you! + +print() + +# Function with multiple parameters +def introduce(name, age, city): + """Introduces a person with their name, age, and city.""" + print(f"Hi! My name is {name}.") + print(f"I am {age} years old.") + print(f"I live in {city}.") + +# Call with multiple arguments (order matters!) +introduce("Charlie", 25, "New York") +print() +introduce("Diana", 30, "San Francisco") + +print() + +# Function with default parameter values +# If no argument is provided, the default value is used +def greet_with_title(name, title="Friend"): + """Greets a person with an optional title.""" + print(f"Hello, {title} {name}!") + +greet_with_title("Emma") # Uses default title "Friend" +greet_with_title("Frank", "Dr.") # Uses provided title "Dr." +greet_with_title("Grace", "Professor") + +print("\n") + + +# ============================================================================ +# FUNCTIONS WITH RETURN VALUES - Send back results +# ============================================================================ + +print("=== FUNCTIONS WITH RETURN VALUES ===\n") + +# Function that returns a value +# 'return' sends a value back to whoever called the function +def add_numbers(a, b): + """Adds two numbers and returns the result.""" + result = a + b + return result # Send the result back + +# Call the function and store the returned value +sum_result = add_numbers(5, 3) +print(f"5 + 3 = {sum_result}") + +# You can use the returned value directly +print(f"10 + 7 = {add_numbers(10, 7)}") + +print() + +# Function with multiple parameters and return value +def calculate_rectangle_area(length, width): + """Calculates the area of a rectangle.""" + area = length * width + return area + +# Use the function +rectangle_area = calculate_rectangle_area(5, 3) +print(f"Rectangle area (5 × 3): {rectangle_area}") + +print() + +# Function that returns different values based on conditions +def check_even_or_odd(number): + """Returns 'even' if number is even, 'odd' if odd.""" + if number % 2 == 0: + return "even" + else: + return "odd" + +# Test the function +print(f"4 is {check_even_or_odd(4)}") +print(f"7 is {check_even_or_odd(7)}") + +print() + +# Function returning multiple values (as a tuple) +def get_min_max(numbers): + """Returns both the minimum and maximum values from a list.""" + minimum = min(numbers) # Built-in function to find smallest value + maximum = max(numbers) # Built-in function to find largest value + return minimum, maximum # Return both values + +# Call the function and unpack the returned values +values = [10, 3, 45, 7, 23] +min_val, max_val = get_min_max(values) +print(f"In {values}:") +print(f"Minimum: {min_val}") +print(f"Maximum: {max_val}") + +print("\n") + + +# ============================================================================ +# PRACTICAL FUNCTION EXAMPLES +# ============================================================================ + +print("=== PRACTICAL EXAMPLES ===\n") + +# Example 1: Temperature converter +def celsius_to_fahrenheit(celsius): + """Converts Celsius to Fahrenheit.""" + fahrenheit = (celsius * 9/5) + 32 + return fahrenheit + +temp_c = 25 +temp_f = celsius_to_fahrenheit(temp_c) +print(f"{temp_c}°C = {temp_f}°F") + +print() + +# Example 2: Grade calculator +def calculate_grade(score): + """Returns a letter grade based on numeric score.""" + if score >= 90: + return "A" + elif score >= 80: + return "B" + elif score >= 70: + return "C" + elif score >= 60: + return "D" + else: + return "F" + +student_score = 85 +grade = calculate_grade(student_score) +print(f"Score: {student_score} → Grade: {grade}") + +print() + +# Example 3: String formatter +def format_name(first_name, last_name): + """Returns a formatted full name in title case.""" + full_name = f"{first_name} {last_name}" + return full_name.title() # Capitalizes first letter of each word + +formatted = format_name("john", "doe") +print(f"Formatted name: {formatted}") + +print() + +# Example 4: List operations +def get_list_statistics(numbers): + """Returns statistics about a list of numbers.""" + total = sum(numbers) # Sum of all numbers + count = len(numbers) # How many numbers + average = total / count # Calculate average + + print(f"Numbers: {numbers}") + print(f"Total: {total}") + print(f"Count: {count}") + print(f"Average: {average}") + + return average # Return just the average + +scores = [85, 90, 78, 92, 88] +avg_score = get_list_statistics(scores) +print(f"The average score is: {avg_score}") + +print("\n") + + +# ============================================================================ +# FUNCTIONS CALLING OTHER FUNCTIONS +# ============================================================================ + +print("=== FUNCTIONS CALLING FUNCTIONS ===\n") + +# Functions can call other functions! +def multiply(x, y): + """Multiplies two numbers.""" + return x * y + +def calculate_circle_area(radius): + """Calculates the area of a circle using the formula: π × r²""" + pi = 3.14159 + # Call multiply function to calculate radius squared + radius_squared = multiply(radius, radius) + area = multiply(pi, radius_squared) + return area + +circle_radius = 5 +circle_area = calculate_circle_area(circle_radius) +print(f"Circle with radius {circle_radius} has area: {circle_area:.2f}") +# Note: {circle_area:.2f} formats the number to 2 decimal places + +print("\n") + + +# ============================================================================ +# VARIABLE SCOPE - Where variables exist +# ============================================================================ + +print("=== VARIABLE SCOPE ===\n") + +# Global variable - can be accessed anywhere +global_message = "I'm global!" + +def demo_scope(): + """Demonstrates local vs global variables.""" + # Local variable - only exists inside this function + local_message = "I'm local!" + + print("Inside function:") + print(f" Local: {local_message}") + print(f" Global: {global_message}") + +demo_scope() + +print("\nOutside function:") +print(f" Global: {global_message}") +print(" Local: Not accessible here! (Would cause an error)") + +print("\n") + + +# ============================================================================ +# WHY USE FUNCTIONS? +# ============================================================================ + +print("=== WHY USE FUNCTIONS? ===\n") + +# Without functions - repetitive code +print("Without functions (repetitive):") +name1 = "Alice" +age1 = 25 +print(f"{name1} will be {age1 + 1} next year") +print(f"{name1} will be {age1 + 5} in 5 years") + +name2 = "Bob" +age2 = 30 +print(f"{name2} will be {age2 + 1} next year") +print(f"{name2} will be {age2 + 5} in 5 years") + +print() + +# With functions - reusable, cleaner code +print("With functions (reusable):") + +def calculate_future_age(name, current_age, years_ahead): + """Calculates and displays future age.""" + future_age = current_age + years_ahead + print(f"{name} will be {future_age} in {years_ahead} year(s)") + +# Now we can reuse this function easily! +calculate_future_age("Alice", 25, 1) +calculate_future_age("Alice", 25, 5) +calculate_future_age("Bob", 30, 1) +calculate_future_age("Bob", 30, 5) + +print("\n") + + +# ============================================================================ +# FUNCTION BEST PRACTICES +# ============================================================================ + +print("=== FUNCTION BEST PRACTICES ===") +print("✓ Give functions descriptive names (use verbs like 'calculate', 'get', 'check')") +print("✓ Functions should do ONE thing and do it well") +print("✓ Use parameters to make functions flexible and reusable") +print("✓ Use return values to send results back") +print("✓ Add docstrings to explain what the function does") +print("✓ Keep functions short and simple (easier to understand and debug)") +print("✓ Use functions to avoid repeating code") + + +# ============================================================================ +# SUMMARY +# ============================================================================ + +print("\n=== SUMMARY ===") +print("Functions are reusable blocks of code that:") +print("1. Are defined with 'def function_name():'") +print("2. Can accept parameters (input)") +print("3. Can return values (output)") +print("4. Help organize code and avoid repetition") +print("5. Make code easier to read, test, and maintain") +print("\nFunctions are one of the most important concepts in programming!") diff --git a/04_data_structures.py b/04_data_structures.py new file mode 100644 index 0000000..a4ad207 --- /dev/null +++ b/04_data_structures.py @@ -0,0 +1,515 @@ +#!/usr/bin/env python3 +""" +04_data_structures.py + +This file demonstrates two fundamental data structures in Python: +- Lists: Ordered, changeable collections of items +- Dictionaries: Key-value pairs for organizing related data + +Data structures help you organize and store multiple pieces of data efficiently. +""" + +# ============================================================================ +# LISTS - Ordered collections of items +# ============================================================================ + +print("=== LISTS ===\n") + +# Creating a list +# Lists are created using square brackets [] +# Items are separated by commas +fruits = ["apple", "banana", "orange", "grape"] +print("List of fruits:", fruits) +print("Type:", type(fruits)) + +print() + +# Lists can contain different data types +mixed_list = [1, "hello", 3.14, True] +print("Mixed list:", mixed_list) + +print() + +# Creating an empty list +empty_list = [] +print("Empty list:", empty_list) + +print("\n") + + +# ============================================================================ +# ACCESSING LIST ITEMS - Using index numbers +# ============================================================================ + +print("=== ACCESSING LIST ITEMS ===\n") + +# Lists are indexed starting from 0 +# First item is at index 0, second at index 1, etc. +colors = ["red", "green", "blue", "yellow"] + +print("All colors:", colors) +print("First color (index 0):", colors[0]) # red +print("Second color (index 1):", colors[1]) # green +print("Third color (index 2):", colors[2]) # blue +print("Fourth color (index 3):", colors[3]) # yellow + +print() + +# Negative indices count from the end +# -1 is the last item, -2 is second-to-last, etc. +print("Last color (index -1):", colors[-1]) # yellow +print("Second-to-last (index -2):", colors[-2]) # blue + +print() + +# List slicing - get a portion of the list +numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +print("All numbers:", numbers) +print("First 3 items [0:3]:", numbers[0:3]) # [0, 1, 2] - stops before index 3 +print("Items 3 to 6 [3:6]:", numbers[3:6]) # [3, 4, 5] - stops before index 6 +print("From index 5 to end [5:]:", numbers[5:]) # [5, 6, 7, 8, 9] +print("Up to index 4 [:4]:", numbers[:4]) # [0, 1, 2, 3] + +print("\n") + + +# ============================================================================ +# MODIFYING LISTS - Change, add, and remove items +# ============================================================================ + +print("=== MODIFYING LISTS ===\n") + +# Lists are mutable (changeable) +fruits = ["apple", "banana", "orange"] +print("Original list:", fruits) + +# Change an item by index +fruits[1] = "strawberry" # Replace "banana" with "strawberry" +print("After changing index 1:", fruits) + +print() + +# Add items to a list +shopping_list = ["milk", "eggs"] +print("Shopping list:", shopping_list) + +# append() adds an item to the end +shopping_list.append("bread") +print("After appending 'bread':", shopping_list) + +# insert() adds an item at a specific position +shopping_list.insert(1, "cheese") # Insert "cheese" at index 1 +print("After inserting 'cheese' at index 1:", shopping_list) + +print() + +# Remove items from a list +tasks = ["homework", "laundry", "shopping", "cleaning"] +print("Tasks:", tasks) + +# remove() removes the first occurrence of a value +tasks.remove("shopping") +print("After removing 'shopping':", tasks) + +# pop() removes and returns an item by index (default: last item) +last_task = tasks.pop() # Removes last item +print(f"Popped '{last_task}':", tasks) + +first_task = tasks.pop(0) # Removes first item (index 0) +print(f"Popped '{first_task}':", tasks) + +print("\n") + + +# ============================================================================ +# LIST OPERATIONS AND METHODS +# ============================================================================ + +print("=== LIST OPERATIONS ===\n") + +# Length of a list +numbers = [10, 20, 30, 40, 50] +print("Numbers:", numbers) +print("Length:", len(numbers)) # How many items in the list + +print() + +# Check if item exists in list +fruits = ["apple", "banana", "orange"] +print("Fruits:", fruits) +print("Is 'banana' in list?", "banana" in fruits) # True +print("Is 'grape' in list?", "grape" in fruits) # False + +print() + +# Sorting a list +unsorted = [3, 1, 4, 1, 5, 9, 2, 6] +print("Original list:", unsorted) + +# sort() modifies the list in place +unsorted.sort() +print("After sort():", unsorted) + +# sorted() returns a new sorted list (doesn't modify original) +names = ["Charlie", "Alice", "Bob"] +sorted_names = sorted(names) +print("Original names:", names) +print("Sorted names:", sorted_names) + +print() + +# Reverse a list +numbers = [1, 2, 3, 4, 5] +print("Original:", numbers) +numbers.reverse() +print("After reverse():", numbers) + +print() + +# List concatenation (combining lists) +list1 = [1, 2, 3] +list2 = [4, 5, 6] +combined = list1 + list2 +print(f"{list1} + {list2} = {combined}") + +print() + +# List repetition +pattern = ["A", "B"] +repeated = pattern * 3 # Repeat the list 3 times +print(f"{pattern} * 3 = {repeated}") + +print("\n") + + +# ============================================================================ +# LOOPING THROUGH LISTS +# ============================================================================ + +print("=== LOOPING THROUGH LISTS ===\n") + +# Use a for loop to access each item +pets = ["dog", "cat", "fish", "bird"] +print("My pets:") +for pet in pets: + print(f"- {pet}") + +print() + +# Loop with index using enumerate() +scores = [85, 92, 78, 95] +print("Test scores:") +for index, score in enumerate(scores): + print(f"Test {index + 1}: {score}") + +print("\n") + + +# ============================================================================ +# LIST COMPREHENSIONS - Create lists efficiently +# ============================================================================ + +print("=== LIST COMPREHENSIONS ===\n") + +# Traditional way: create a list of squares +squares = [] +for i in range(1, 6): + squares.append(i * i) +print("Squares (traditional way):", squares) + +# List comprehension: more concise way +squares = [i * i for i in range(1, 6)] +print("Squares (list comprehension):", squares) + +print() + +# List comprehension with condition +# Get only even numbers from 0 to 10 +evens = [num for num in range(11) if num % 2 == 0] +print("Even numbers:", evens) + +print("\n") + + +# ============================================================================ +# DICTIONARIES - Key-value pairs +# ============================================================================ + +print("=== DICTIONARIES ===\n") + +# Creating a dictionary +# Dictionaries use curly braces {} with key:value pairs +student = { + "name": "Alice", + "age": 20, + "grade": "A", + "enrolled": True +} + +print("Student dictionary:", student) +print("Type:", type(student)) + +print() + +# Creating an empty dictionary +empty_dict = {} +print("Empty dictionary:", empty_dict) + +print("\n") + + +# ============================================================================ +# ACCESSING DICTIONARY VALUES - Using keys +# ============================================================================ + +print("=== ACCESSING DICTIONARY VALUES ===\n") + +# Access values using keys in square brackets +person = { + "name": "Bob", + "age": 25, + "city": "New York" +} + +print("Person:", person) +print("Name:", person["name"]) # Access value with key "name" +print("Age:", person["age"]) +print("City:", person["city"]) + +print() + +# Using get() method (safer - doesn't error if key doesn't exist) +print("Name (using get):", person.get("name")) +print("Country (using get):", person.get("country", "Not specified")) +# get() with default value: if key doesn't exist, returns the default + +print("\n") + + +# ============================================================================ +# MODIFYING DICTIONARIES - Add, change, and remove items +# ============================================================================ + +print("=== MODIFYING DICTIONARIES ===\n") + +# Dictionaries are mutable (changeable) +car = { + "brand": "Toyota", + "model": "Camry", + "year": 2020 +} + +print("Original car:", car) + +# Change a value +car["year"] = 2021 # Update the year +print("After changing year:", car) + +print() + +# Add a new key-value pair +car["color"] = "blue" # Add new key "color" +print("After adding color:", car) + +print() + +# Remove a key-value pair +car.pop("model") # Remove the "model" key +print("After removing model:", car) + +# Alternative: use del +del car["year"] +print("After deleting year:", car) + +print("\n") + + +# ============================================================================ +# DICTIONARY METHODS AND OPERATIONS +# ============================================================================ + +print("=== DICTIONARY METHODS ===\n") + +book = { + "title": "Python Basics", + "author": "John Doe", + "pages": 300, + "rating": 4.5 +} + +print("Book:", book) + +# Get all keys +print("Keys:", list(book.keys())) + +# Get all values +print("Values:", list(book.values())) + +# Get all key-value pairs as tuples +print("Items:", list(book.items())) + +print() + +# Check if key exists +print("Does 'title' exist?", "title" in book) # True +print("Does 'price' exist?", "price" in book) # False + +print() + +# Length of dictionary (number of key-value pairs) +print("Number of items:", len(book)) + +print("\n") + + +# ============================================================================ +# LOOPING THROUGH DICTIONARIES +# ============================================================================ + +print("=== LOOPING THROUGH DICTIONARIES ===\n") + +scores = { + "Alice": 95, + "Bob": 87, + "Charlie": 92 +} + +# Loop through keys +print("Students:") +for name in scores: + print(f"- {name}") + +print() + +# Loop through key-value pairs +print("Scores:") +for name, score in scores.items(): + print(f"{name}: {score}") + +print("\n") + + +# ============================================================================ +# NESTED DATA STRUCTURES - Lists in dictionaries, dictionaries in lists +# ============================================================================ + +print("=== NESTED DATA STRUCTURES ===\n") + +# Dictionary containing a list +student = { + "name": "Diana", + "grades": [85, 90, 88, 92], # List inside dictionary + "subjects": ["Math", "Science", "English"] +} + +print("Student:", student) +print("Name:", student["name"]) +print("Grades:", student["grades"]) +print("First grade:", student["grades"][0]) # Access list item + +print() + +# List of dictionaries +students = [ + {"name": "Alice", "age": 20, "grade": "A"}, + {"name": "Bob", "age": 21, "grade": "B"}, + {"name": "Charlie", "age": 19, "grade": "A"} +] + +print("All students:") +for student in students: + print(f" {student['name']}, age {student['age']}, grade {student['grade']}") + +print("\n") + + +# ============================================================================ +# PRACTICAL EXAMPLES +# ============================================================================ + +print("=== PRACTICAL EXAMPLES ===\n") + +# Example 1: Phonebook using dictionary +phonebook = { + "Alice": "555-1234", + "Bob": "555-5678", + "Charlie": "555-9012" +} + +print("Phonebook:") +for name, number in phonebook.items(): + print(f"{name}: {number}") + +print() + +# Example 2: Inventory using dictionary +inventory = { + "apples": 50, + "bananas": 30, + "oranges": 45 +} + +print("Inventory:") +for item, quantity in inventory.items(): + print(f"{item.capitalize()}: {quantity}") + +# Add to inventory +inventory["bananas"] += 20 # Add 20 bananas +print(f"After restocking bananas: {inventory['bananas']}") + +print() + +# Example 3: Student grade tracker using nested structures +classroom = { + "students": ["Alice", "Bob", "Charlie"], + "grades": { + "Alice": [85, 90, 88], + "Bob": [78, 82, 85], + "Charlie": [92, 95, 90] + } +} + +print("Grade Report:") +for student in classroom["students"]: + grades = classroom["grades"][student] + average = sum(grades) / len(grades) + print(f"{student}: {grades} → Average: {average:.1f}") + +print("\n") + + +# ============================================================================ +# CHOOSING BETWEEN LISTS AND DICTIONARIES +# ============================================================================ + +print("=== WHEN TO USE LISTS VS DICTIONARIES ===") +print("\nUse LISTS when:") +print(" ✓ You have a sequence of items") +print(" ✓ Order matters") +print(" ✓ You need to access items by position/index") +print(" ✓ Items are similar (like a list of names)") +print("\nUse DICTIONARIES when:") +print(" ✓ You have key-value relationships") +print(" ✓ You need to look up values by name (key)") +print(" ✓ Order doesn't matter (though Python 3.7+ maintains insertion order)") +print(" ✓ Items have different attributes (like a person's details)") + + +# ============================================================================ +# SUMMARY +# ============================================================================ + +print("\n=== SUMMARY ===") +print("LISTS:") +print(" - Created with []: my_list = [1, 2, 3]") +print(" - Ordered and indexed (start at 0)") +print(" - Access by index: my_list[0]") +print(" - Mutable: can change, add, remove items") +print(" - Methods: append(), insert(), remove(), pop(), sort()") +print("\nDICTIONARIES:") +print(" - Created with {}: my_dict = {'key': 'value'}") +print(" - Key-value pairs") +print(" - Access by key: my_dict['key']") +print(" - Mutable: can change, add, remove items") +print(" - Methods: keys(), values(), items(), get()") +print("\nBoth are essential for organizing data in Python!") diff --git a/README.md b/README.md index 845e38f..00f55a0 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,57 @@ # python-coding-examples-template A collection of basic Python coding examples for RobotX Workshops students. + +## Purpose +This repository contains simple, heavily-commented Python examples designed to help beginners learn fundamental programming concepts. Each file focuses on a specific topic and includes detailed explanations to make learning easy and accessible. + +## Files Overview + +### 01_variables.py +Learn about basic data types in Python: +- **int**: Whole numbers (e.g., 5, -10, 100) +- **float**: Decimal numbers (e.g., 3.14, -0.5, 2.0) +- **string**: Text data (e.g., "Hello", 'Python') +- **bool**: True/False values + +### 02_control_flow.py +Understand how to control program flow: +- **if/else statements**: Make decisions in your code +- **for loops**: Repeat actions a specific number of times +- **while loops**: Repeat actions while a condition is true + +### 03_functions.py +Learn to create reusable code: +- **Defining functions**: Create your own functions +- **Arguments**: Pass data into functions +- **Return values**: Get results back from functions + +### 04_data_structures.py +Work with collections of data: +- **Lists**: Ordered collections of items that can be changed +- **Dictionaries**: Key-value pairs for organizing related data + +## How to Use + +1. Make sure you have Python installed on your computer (Python 3.x) +2. Open each file in your favorite text editor or IDE +3. Read through the comments to understand what each line does +4. Run each file to see the output: + ```bash + python3 01_variables.py + python3 02_control_flow.py + python3 03_functions.py + python3 04_data_structures.py + ``` +5. Experiment by modifying the code and running it again! + +## Learning Tips +- Start with `01_variables.py` and work through the files in order +- Read all the comments carefully - they explain what's happening +- Try changing values and see what happens +- Don't be afraid to break things - that's how you learn! +- Run the code frequently to see how your changes affect the output + +## Getting Help +If you get stuck or have questions, don't hesitate to ask your instructor or workshop facilitator! + +Happy coding! 🚀