You have already used built-in tools like
print() and len(). Now you will build your own. A function is a named block of code that performs one specific task. Instead of repeating the same lines every time, you write them once inside a function and call it whenever needed.Defining Your First Function
def say_hello():
print("Hi there!")
# Call the function by using its name and parentheses
say_hello()The
def keyword starts a definition. The word after it is the name. You use this name to call the function later. Everything indented under the colon belongs inside that block. When Python sees say_hello(), it jumps into those lines, runs them, and then comes back.Parameters: Giving Instructions
def greet_user(name):
print(f"Hello, {name}!")
# 'Alice' is the argument passed to parameter 'name'
greet_user("Alice")
greet_user("Bob")name inside def greet_user(name) is a parameter. It acts as a placeholder. When you call the function with "Alice", name holds that string for the whole of that call. This makes your code flexible and reusable for any name.return: Sending Data Back
# This only displays; nothing is returned
# (It returns None implicitly)
def show_total(price, tax):
print(price + tax)
# This sends the number back
def calc_total(price, tax):
return price + tax
total = calc_total(10.50, 2.0) # total is now a float (12.5)
print(total * 2) # Prints 25.0print and return.If you use only
print(), the result is just a visual display; it vanishes immediately. If you use return, Python hands that value back to your main code. You can then assign it to a variable, like total above, and perform further arithmetic or logic on it.Default Values
def greet(name="friend"):
return f"Hello, {name}!"
# Call without arguments: uses the default
print(greet())
# Call with an argument: overrides the default
print(greet("Sam"))You can assign a default value to any parameter. If you call the function without providing that argument, Python uses the default. This is useful when one input often stays the same across many calls. You only need to pass it if you want something different.