18. Introduction to Python Functions

Quiz: 0/5

Functions are like mini-programs within your program. They allow you to write a block of code once and use it multiple times by calling the function's name. Functions can also take inputs (arguments) and return outputs.

Why use Functions?

  • Code Reusability: Write once, use it anywhere.
  • Organization: Break large programs into smaller, more manageable pieces.
  • Readability: Makes your code easier to read and understand.
  • Debugging: Easier to test and debug specific parts of your code.

Defining a Function in Python

To define a function, use the def keyword followed by the function name and parentheses.
Here’s the syntax:

def function_name(parameters):
    # Code block
    return value

Example: A simple Function

Let’s create a function that greets someone:

def greet():
    print("Hello! Welcome to Python programming.")
  • def: Defines the function.
  • greet: Name of the function.
  • print("..."): Code inside the function.

You can call this function like so:

greet()
# Output: Hello! Welcome to Python programming.

Adding parameters

Parameters allow you to pass information to functions. For example:

def greet_person(name):
    print(f"Hello, {name}! Welcome to Python programming.")

Now, you can call it with different names:

greet_person("Alice")
# Output: Hello, Alice! Welcome to Python programming.

greet_person("Bob")
# Output: Hello, Bob! Welcome to Python programming.

Using return to get outputs

Functions can return values to the code that called them:

def add_numbers(a, b):
    return a + b

Call the function and store the result:

result = add_numbers(3, 5)
print(result)
# Output: 8

Scope: where variables live

  • Local Variables: Exist only inside the function.
  • Global Variables: Exist everywhere in your program.

Example:

x = 10  # Global variable

def multiply_by_two():
    x = 5  # Local variable
    return x * 2

print(multiply_by_two())  # Output: 10
print(x)  # Output: 10 (global x is unchanged)

Conclusion

Functions are powerful tools that make your code more efficient and easier to manage. By learning to define and use them, you’re taking a significant step toward writing better programs!

Hands-On Practise

Exercise: Create and use Functions

Problem Statement

Create a function called calculate_discounted_price that:

  1. Takes two arguments:
    • price (the original price of an item).
    • discount (the discount percentage).
  2. Calculates the discounted price using the formula: discounted price = price X (1− (discount/100)​)
  3. Returns the discounted price.

Then, test your function with the following cases:

  • Original price: 100, Discount: 10
  • Original price: 250, Discount: 20
  • Original price: 50, Discount: 5

Hints

  • Use the return keyword to send the result back from your function.
  • Use print() to display the results in a formatted string.
Output:

Quizzes: 0/5

Question 1:

What is the purpose of the 'def' keyword in Python?

  • To define a function.
  • To call a function.
  • To return a value from a function.
  • To create a variable.

Question 2:

Which of the following is the correct way to define a function that takes two arguments, 'a' and 'b'?

  • def function(a, b):
  • function def(a, b):
  • def a, b function():
  • function def() a, b:

Question 3:

What will the following code do? `python def greet(name): print(f'Hello, {name}!') greet('Alice') `

  • Print 'Hello, Alice!'
  • Return 'Hello, Alice!'
  • Create a function named 'Alice'
  • Create a variable named 'name'

Question 4:

What does the 'return' statement do in a function?

  • It exits the function and provides the result to the caller.
  • It prints the result of the function.
  • It defines the function's parameters.
  • It calls the function.

Question 5:

Which of the following is NOT a reason to use functions in Python?

  • To reuse code and avoid repetition.
  • To break code into smaller, more manageable pieces.
  • To make the code harder to read.
  • To organize code in a structured way.

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonFile HandlingNext lessonError and exception handling