A function is a named block of code that performs a specific task, like a mini-program inside your main program. It lets you group related instructions together so you can run them whenever needed without rewriting the same lines over and over. Think of it as a vending machine: you input something (like coins), and it outputs something useful (like a snack) based on its built-in rules. Functions make your code cleaner and more efficient, especially as projects grow bigger.
Description: This is where you create the instructions for a specific task. You use the keyword def to tell Python you are starting a new set of instructions that you want it to remember for later.
defgreet_user(): print("Hello! Welcome to our website- estudy247.com")
Calling a Function
Defining a function doesn’t actually run the code; it just stores it. You tell Python to execute those saved instructions.
Description: To make a function work, you simply type its name followed by parentheses (). This tells the program to jump to those instructions, run them, and then come back to where it left off.
defgreet_user(): print("Hello! Welcome to our website- estudy247.com")
# This actually triggers the "Hello!" message function greet_user() # output: Hello! Welcome to our website- estudy247.com
Function Arguments
Parameters are like input boxes for a function. They allow us to pass values into the function to use inside it.
Description: Arguments are placeholders you put inside the parentheses when you create the function. When you call the function, you provide the actual “ingredients” (data) you want the function to use.
Some functions just perform a task (like printing text), but others create something and give it back to you. Think of a juice machine: you put in an orange (input), and it “returns” a glass of juice (output) for you to use elsewhere.
Description: The return keyword tells Python to send a result back to the part of the program that called it. This allows you to save the result of a function into a variable to use later.
defadd_numbers(a, b): returna+b
total=add_numbers(5, 10) print(total) #output: 15
Default Parameters
A Default Parameter is like a “backup” choice. If you don’t provide a specific value, the function will use the one you pre-selected as the standard.
Description: You set a default value in the function definition. If the user provides their own value, Python uses that; if they leave it blank, Python uses the default value you provided.
defmake_coffee(type="Black"): print("Making a cup of "+type+" coffee.")
make_coffee() # Uses default: Black make_coffee("Latte") # Uses your choice: Latte
Variable Number of Arguments
Sometimes we don’t know how many values will be passed. Using *args or **kwargs, a function can handle many inputs.
deftotal_score(*args): # Collects all as a tuple returnsum(args)