
Python
Functions are blocks of code you write once and use many times. They make your code cleaner, easier to understand, and way less repetitive.
A function is like a recipe. You write the steps once, then whenever you need the result, you just follow the recipe.
def greet():
print("Hello, World!")
greet() # Use the function
greet() # Use it again
greet() # Use it againWhen you run this, "Hello, World!" prints three times. Instead of writing `print("Hello, World!")` three times, you wrote it once in the function.
Without functions, you'd repeat the same code over and over:
# Without functions - repetitive
print("Welcome to the app!")
print("Welcome to the app!")
print("Welcome to the app!")
# With functions - clean
def welcome():
print("Welcome to the app!")
welcome()
welcome()
welcome()Functions let you name what your code does:
def calculate_total():
return 50 + 30
total = calculate_total() # Clear what this does!If you need to change something, you only change it in one place:
def welcome():
print("Welcome to the app!") # If you change this...
# ...it changes everywhere the function is usedUse the `def` keyword:
def say_hello():
print("Hi there!")
say_hello() # Call/use the function
# Output: Hi there!How it works:
1. `def` tells Python you're creating a function
2. `say_hello()` is the function name
3. `print("Hi there!")` is the code inside the function
4. `say_hello()` calls/runs the function
Imagine you're making a chatbot that greets people:
def greet_customer():
print("Hello! Welcome to our store.")
print("How can I help you today?")
greet_customer() # Customer walks in
greet_customer() # Another customer walks in
greet_customer() # Another oneWithout functions, you'd repeat those two lines of code every time. With functions, you just call `greet_customer()`.
1. Functions start with `def`
2. Functions have a name (like `greet`, `calculate`, etc.)
3. Code inside is indented (4 spaces)
4. Call a function with parentheses `function_name()`
def say_goodbye(): # Step 1: def keyword
print("Goodbye!") # Step 3: indented code
say_goodbye() # Step 4: call with ()| Concept | Remember |
|---|---|
| Function | A block of code with a name |
| def keyword | How you create a function |
| Indentation | Code inside function must be indented |
| Call function | Use the name with `()` to run it |
| Reusable | Write once, use many times |
Now that you know what functions are, let's learn how to make functions accept different data using parameters.
Next: Parameters & Arguments →
Ready to practice? Try challenges or view solutions
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward