πŸ”§ How to Code in Python: Part 6 & 7 β€” Functions, Scope, Dictionaries, and Built-In Tools

You’ve made it this far β€” your Python scripts can now take input, use logic, and loop through data. In this double-feature post, we’re diving into two powerful tools that will make your programs smarter and cleaner:

  • ✨ Functions (reusable blocks of code)
  • πŸ”‘ Dictionaries (key-value data structures)
  • 🧰 Useful built-in Python functions

πŸ§ͺ Part 6: Writing Your First Functions

πŸ›  Step 1: Creating a Simple Function

You define a function using the def keyword:

def greet():
    print("Hello there!")

Call it like this:

greet()

Output:

Hello there!

🧩 Step 2: Parameters and Input

Functions can take parameters (custom input):

def greet(name):
    print("Hello,", name)

greet("Angelus")
greet("May")

Output:

Hello, Angelus
Hello, May

πŸ” Step 3: Returning Values

You can return values instead of just printing them:

def add(a, b):
    return a + b

result = add(5, 3)
print("Sum is:", result)

Output:

Sum is: 8

πŸ” return sends data back to wherever the function was called. Without it, the function just runs and exits.


🌍 Step 4: Local vs Global Scope

Local variables exist only inside a function:

def secret_code():
    code = 12345
    print("Inside:", code)

secret_code()
# print(code)  ❌ will cause an error

Global variables exist everywhere, but use them sparingly:

username = "Angelus"

def welcome():
    print("Welcome,", username)

welcome()

βœ… Prefer passing variables into functions instead of relying on global scope.


🧼 Step 5: Clean Function Design

  • Keep functions short
  • Give them descriptive names
  • One function = one task

Example:

def calculate_discount(price, percent):
    discount = price * (percent / 100)
    return price - discount

πŸ“¦ Part 7: Python Dictionaries and Built-in Power Tools

πŸ”‘ Step 1: What Is a Dictionary?

A dictionary is a collection of key-value pairs:

user = {
    "name": "Angelus",
    "age": 29,
    "city": "Chicago"
}

Access values by key:

print(user["name"])  # Angelus

πŸ›  Step 2: Adding, Updating, and Deleting

user["email"] = "angel@example.com"   # Add new
user["age"] = 30                      # Update
del user["city"]                      # Delete

πŸ” Step 3: Looping Through a Dictionary

for key, value in user.items():
    print(key, "β†’", value)

Output:

name β†’ Angelus
age β†’ 30
email β†’ angel@example.com

Other helpful methods:

user.keys()     # All keys
user.values()   # All values
user.get("age") # Safe access

🧰 Step 4: Handy Built-In Functions

These are tools Python gives you out of the box:

len()     # Length of a string, list, or dict
type()    # Type of any variable
str()     # Convert to string
int()     # Convert to integer
sum()     # Add up numbers in a list
range()   # Generate number sequences
input()   # Get input from a user

Example:

nums = [5, 10, 15]
print("Total:", sum(nums))

Output:

Total: 30

βœ… Recap: What You Learned

Functions:

  • Defined with def
  • Can accept input and return values
  • Keep your code clean and reusable
  • Scope determines where variables exist

Dictionaries:

  • Store data as key-value pairs
  • Easily loop through and access by key
  • Used everywhere in Python apps

Built-in functions:

  • Save time and help you write less code
  • Great for working with strings, lists, and numbers

⏭️ Coming Up Next: Error Handling + File I/O

Next time we’ll handle real-world stuff:

  • Catching errors with try/except
  • Reading and writing to files
  • Keeping your scripts crash-proof and useful

Stay sharp β€” you’re almost through the full beginner track!

Leave a comment