Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
65: Defining and Calling Functions
Wait, so how do I actually define a function and then make it do something?
Think of defining a function as writing a recipe. When you write the recipe down, you aren't actually cooking anything; you're just documenting the steps for later. In Python, we use the def keyword to "write the recipe."
Here is a simple example. Let's say we're building a small e-commerce tool and we need to calculate a final price after a tax is added. I'll define the function first, and then "call" it to actually run the code.
def apply_sales_tax():
price = 100
tax_rate = 0.07
total = price + (price * tax_rate)
print(f"The total price is ${total}")
# At this point, nothing has happened on the screen.
# To actually execute that code, I have to call it:
apply_sales_tax()
I've seen a lot of beginners write the def block and then wonder why their program doesn't do anything. Remember: the definition just stores the logic. The parentheses () at the end are what tell Python, "Okay, go run that block of code now."
What's the deal with the stuff inside the parentheses?
In the example above, the function is pretty useless because it always calculates the tax for $100. To make it actually helpful, we need to pass it different values. This is where parameters come in. Parameters are essentially placeholders for the data you'll provide when you call the function.
Instead of hardcoding 100, I'll let the function accept any price and any tax rate:
def apply_sales_tax(price, tax_rate):
total = price + (price * tax_rate)
print(f"The total price is ${total}")
# Now I can reuse this same logic for different items
apply_sales_tax(19.99, 0.05) # A cheap item with 5% tax
apply_sales_tax(1200.00, 0.08) # A laptop with 8% tax
You can think of price and tax_rate as temporary variables that only exist inside that function. This is great because it keeps your main code clean and prevents you from having to write the same math over and over again.
Why do I need "return" if I can just print the result inside the function?
This is one of the biggest sticking points when I'm mentoring new devs. print() is for humans; return is for the computer. When you use print(), you're just splashing text onto the screen. But what if you need to use that calculated total to update a database or add it to a shopping cart total?
If a function doesn't have a return statement, it effectively returns None. If you try to save the result of a "print-only" function to a variable, that variable will be empty.
Watch the difference here:
def get_discounted_price(price, discount):
# Instead of printing, we SEND the value back to whoever called the function
return price - discount
# Now I can capture that value in a variable and keep working with it
final_bill = get_discounted_price(100, 15)
shipping_cost = 5.00
# I can perform more math because 'final_bill' actually holds a number
grand_total = final_bill + shipping_cost
print(f"Your grand total is ${grand_total}")
In the real world, you'll use return about 95% of the time. You want your functions to be like little machines: you feed them raw materials (arguments), and they spit out a finished product (return value) that you can use elsewhere in your app.
📋 Practical Task
Building a Member-Only Discount Tool
You are writing a checkout system for a store. You need to create a function that calculates the final price of an item based on whether the customer is a loyalty member or not.
Requirements:
- Define a function called
calculate_member_pricethat takes two parameters:original_priceandis_member(a boolean). - If
is_memberisTrue, the function should apply a 20% discount to the price. - If
is_memberisFalse, the function should return the original price. - The function must return the final value, not just print it.
- Call the function twice: once for a member and once for a non-member, and print the results to verify they are correct.
There are no comments for now.