Course Content
Introduction to Python (copy)
Introduction to Python (copy)
User Defined Functions
A user-defined function is a block of code that you create to perform a specific task. Unlike built-in functions, which are provided by Python, user-defined functions are written by you to solve specific problems in your programs. Once defined, these functions can be reused multiple times, making your code more organized, efficient, and easier to maintain.
Now, let's watch as Alex demonstrates how to create and use user-defined functions to simplify tasks:
The basic structure of a user-defined function in Python looks like this:
python
def
: this keyword is used to start the definition of a function;function_name
: this is the name you give to your function. It should be descriptive of what the function does, making your code more readable;argument_1, argument_2
: these are the names of the variables that you pass into the function. They act as placeholders for the values that you'll provide when calling the function. A function can have zero or more parameters;- The colon
:
signifies the start of the function's code block; # Code block
: this is the body of the function, where you write the code that the function will execute. It must be indented just like when writing loops or conditional statements;return
: this statement is used to exit the function and return a result. Not all functions need a return statement, but it's useful when you want to send a value back to where the function was called.
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.
def greet_customer(name): print(f"Hello, {name}! Welcome to our store.") greet_customer("Alice")
Note
In the example above,
name
is the parameter, and the string"Alice"
is the argument.
Void Functions
As shown above, not all functions need to return a value. Some functions perform a task but don't return anything to the caller. These are known as void functions.
In Python, a void function is a user-defined function that either lacks a return
statement or has a return
statement that doesn't return any value. In both cases, the function will return None
by default.
In the example above, greet_customer()
is a void function because it performs the action of printing a greeting but doesn't return any result that can be stored or used elsewhere in the program.
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.
# 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)
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.
# `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}")
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
andquantity
. - Inside the function, multiply
price
byquantity
to get the total cost. - Return the result from the function.
Output Requirements
- Call
calculate_total_cost()
withprice = 1.50
andquantity = 10
. - Print the result as:
The total cost for apples is $<apples_total_cost>
Solution
Thanks for your feedback!
User Defined Functions
A user-defined function is a block of code that you create to perform a specific task. Unlike built-in functions, which are provided by Python, user-defined functions are written by you to solve specific problems in your programs. Once defined, these functions can be reused multiple times, making your code more organized, efficient, and easier to maintain.
Now, let's watch as Alex demonstrates how to create and use user-defined functions to simplify tasks:
The basic structure of a user-defined function in Python looks like this:
python
def
: this keyword is used to start the definition of a function;function_name
: this is the name you give to your function. It should be descriptive of what the function does, making your code more readable;argument_1, argument_2
: these are the names of the variables that you pass into the function. They act as placeholders for the values that you'll provide when calling the function. A function can have zero or more parameters;- The colon
:
signifies the start of the function's code block; # Code block
: this is the body of the function, where you write the code that the function will execute. It must be indented just like when writing loops or conditional statements;return
: this statement is used to exit the function and return a result. Not all functions need a return statement, but it's useful when you want to send a value back to where the function was called.
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.
def greet_customer(name): print(f"Hello, {name}! Welcome to our store.") greet_customer("Alice")
Note
In the example above,
name
is the parameter, and the string"Alice"
is the argument.
Void Functions
As shown above, not all functions need to return a value. Some functions perform a task but don't return anything to the caller. These are known as void functions.
In Python, a void function is a user-defined function that either lacks a return
statement or has a return
statement that doesn't return any value. In both cases, the function will return None
by default.
In the example above, greet_customer()
is a void function because it performs the action of printing a greeting but doesn't return any result that can be stored or used elsewhere in the program.
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.
# 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)
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.
# `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}")
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
andquantity
. - Inside the function, multiply
price
byquantity
to get the total cost. - Return the result from the function.
Output Requirements
- Call
calculate_total_cost()
withprice = 1.50
andquantity = 10
. - Print the result as:
The total cost for apples is $<apples_total_cost>
Solution
Thanks for your feedback!