Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn User Defined Functions | Functions
Introduction to Python

bookUser Defined Functions

A user-defined function is a reusable block of code that you write to do a specific job. You can call this function whenever you need to perform that task, which helps keep your code organized and efficient.

A user-defined function in Python follows this basic structure:

def function_name(parameter1, parameter2):
    # Code block
    return result
  • def: starts the function definition;
  • function_name: the name you choose for your function;
  • parameter1, parameter2: placeholders for values you pass to the function;
  • :: marks the start of the function's code block;
  • Code block: the indented code that runs when the function is called;
  • return: sends a value back to where the function was called (optional).

Parameters and Arguments

Parameters are the variables listed inside the parentheses in the function definition. They are used to receive values (arguments) that are passed into the function.

Arguments are the actual values you provide to the function when you call it. These values are assigned to the function's parameters.

1234
def greet_customer(name): print(f"Hello, {name}! Welcome to our store.") greet_customer("Alice")
copy
Note
Note

In the example above, name is the parameter, and the string "Alice" is the argument.

Void Functions

Some functions perform an action but do not return a value. These are called void functions. For example, a function that prints a message or updates something on the screen does not give back a result you can use later.

In Python, if a function does not have a return statement, or if it uses return without a value, the function ends and returns None automatically. You can use return by itself to stop the function early, even if you do not want to send back a value.

Void Function Example

Here's another example of a void function where the return statement is used to terminate the function's execution but still doesn't return any value.

123456789101112131415161718192021
# Function to check stock levels of grocery items def check_stock(inventory): for item, stock in inventory.items(): if stock < 10: print(f"Warning: {item} is running low on stock with only {stock} units left!") print("Please restock the item before proceeding with the check.") return # Stops the function if stock is below 10 print(f"{item} has sufficient stock: {stock} units.") print("All items have sufficient stock.") # Example inventory of a grocery store inventory = { "Apples": 50, "Bananas": 30, "Milk": 8, # This will trigger the early exit "Bread": 25 } # Check stock levels check_stock(inventory)
copy

This code checks stock levels in a grocery store and stops if any item is running low.

The check_stock function goes through each item in the inventory dictionary. For every item, it checks the stock amount. If the stock is less than 10, it prints a warning message and uses return to stop the function immediately.

If the stock is sufficient, it prints a confirmation message and continues checking the next item. If no low-stock items are found, the function prints a final message saying all items have enough stock.

Example Application

Now, let's consider a function that returns a specific value. For example, if you often need to calculate discounts for different products in your store, you can create a function to perform the discount calculation. This function can then be reused whenever necessary.

1234567891011121314
# `cost` and `discount_rate` are the parameters of the function def calculate_discounted_price(cost, discount_rate): final_price = cost * (1 - discount_rate) return final_price # Call the `calculate_discounted_price` function and pass in `cost` and `discount_rate` values as arguments apples_final_price = calculate_discounted_price(1.2, 0.10) milk_final_price = calculate_discounted_price(2.2, 0.15) bread_final_price = calculate_discounted_price(0.8, 0.05) # Display the discounted prices print(f"The discounted price of apples is ${apples_final_price}") print(f"The discounted price of milk is ${milk_final_price}") print(f"The discounted price of bread is ${bread_final_price}")
copy
Task

Swipe to start coding

Define a function to calculate the total cost of a product by multiplying its price and quantity sold.

  • Create a function called calculate_total_cost() that takes two parameters: price and quantity.
  • Inside the function, multiply price by quantity to get the total cost.
  • Return the result from the function.

Output Requirements

  • Call calculate_total_cost() with price = 1.50 and quantity = 10.
  • Print the result as:
    The total cost for apples is $<apples_total_cost>

Solution

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 6. ChapterΒ 3
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

close

bookUser Defined Functions

Swipe to show menu

A user-defined function is a reusable block of code that you write to do a specific job. You can call this function whenever you need to perform that task, which helps keep your code organized and efficient.

A user-defined function in Python follows this basic structure:

def function_name(parameter1, parameter2):
    # Code block
    return result
  • def: starts the function definition;
  • function_name: the name you choose for your function;
  • parameter1, parameter2: placeholders for values you pass to the function;
  • :: marks the start of the function's code block;
  • Code block: the indented code that runs when the function is called;
  • return: sends a value back to where the function was called (optional).

Parameters and Arguments

Parameters are the variables listed inside the parentheses in the function definition. They are used to receive values (arguments) that are passed into the function.

Arguments are the actual values you provide to the function when you call it. These values are assigned to the function's parameters.

1234
def greet_customer(name): print(f"Hello, {name}! Welcome to our store.") greet_customer("Alice")
copy
Note
Note

In the example above, name is the parameter, and the string "Alice" is the argument.

Void Functions

Some functions perform an action but do not return a value. These are called void functions. For example, a function that prints a message or updates something on the screen does not give back a result you can use later.

In Python, if a function does not have a return statement, or if it uses return without a value, the function ends and returns None automatically. You can use return by itself to stop the function early, even if you do not want to send back a value.

Void Function Example

Here's another example of a void function where the return statement is used to terminate the function's execution but still doesn't return any value.

123456789101112131415161718192021
# Function to check stock levels of grocery items def check_stock(inventory): for item, stock in inventory.items(): if stock < 10: print(f"Warning: {item} is running low on stock with only {stock} units left!") print("Please restock the item before proceeding with the check.") return # Stops the function if stock is below 10 print(f"{item} has sufficient stock: {stock} units.") print("All items have sufficient stock.") # Example inventory of a grocery store inventory = { "Apples": 50, "Bananas": 30, "Milk": 8, # This will trigger the early exit "Bread": 25 } # Check stock levels check_stock(inventory)
copy

This code checks stock levels in a grocery store and stops if any item is running low.

The check_stock function goes through each item in the inventory dictionary. For every item, it checks the stock amount. If the stock is less than 10, it prints a warning message and uses return to stop the function immediately.

If the stock is sufficient, it prints a confirmation message and continues checking the next item. If no low-stock items are found, the function prints a final message saying all items have enough stock.

Example Application

Now, let's consider a function that returns a specific value. For example, if you often need to calculate discounts for different products in your store, you can create a function to perform the discount calculation. This function can then be reused whenever necessary.

1234567891011121314
# `cost` and `discount_rate` are the parameters of the function def calculate_discounted_price(cost, discount_rate): final_price = cost * (1 - discount_rate) return final_price # Call the `calculate_discounted_price` function and pass in `cost` and `discount_rate` values as arguments apples_final_price = calculate_discounted_price(1.2, 0.10) milk_final_price = calculate_discounted_price(2.2, 0.15) bread_final_price = calculate_discounted_price(0.8, 0.05) # Display the discounted prices print(f"The discounted price of apples is ${apples_final_price}") print(f"The discounted price of milk is ${milk_final_price}") print(f"The discounted price of bread is ${bread_final_price}")
copy
Task

Swipe to start coding

Define a function to calculate the total cost of a product by multiplying its price and quantity sold.

  • Create a function called calculate_total_cost() that takes two parameters: price and quantity.
  • Inside the function, multiply price by quantity to get the total cost.
  • Return the result from the function.

Output Requirements

  • Call calculate_total_cost() with price = 1.50 and quantity = 10.
  • Print the result as:
    The total cost for apples is $<apples_total_cost>

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 6. ChapterΒ 3
single

single

some-alt