Learn Python in 30 Days - Day 6: Functions in Python

Rifat Seniabad
By -
0

 Learn Python in 30 Days - Day 6: Functions in Python


Welcome to Day 6! Functions are one of the most important building blocks in Python. They allow you to organize your code into reusable chunks, making it more readable, modular, and efficient. Let’s explore how to create and use functions!


1. What is a Function?

A function is a block of reusable code that performs a specific task. You can use functions to:

  • Reduce redundancy.
  • Make your code more readable.
  • Reuse code across your program.

2. Types of Functions

  1. Built-in Functions: Functions provided by Python (e.g., print(), len()).
  2. User-defined Functions: Functions you create yourself.

3. Defining a Function

Syntax:

def function_name(parameters):
    # Code block
    return value  # Optional

Example:

def greet():
    print("Hello, welcome to Python!")

Calling the Function:

greet()

Output:

Hello, welcome to Python!

4. Function Parameters

Functions can accept parameters (inputs) to work with.

Example with Parameters:

def greet_user(name):
    print(f"Hello, {name}!")

Calling the Function:

greet_user("Alice")

Output:

Hello, Alice!

Multiple Parameters:

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

result = add_numbers(5, 3)
print("Sum:", result)

Output:

Sum: 8

5. Default Parameter Values

You can set default values for parameters.

Example:

def greet_user(name="Guest"):
    print(f"Hello, {name}!")

Calling the Function:

greet_user()  # Uses default value
greet_user("Bob")  # Overrides default value

Output:

Hello, Guest!
Hello, Bob!

6. Return Statement

The return statement sends a value back to the caller.

Example:

def multiply(a, b):
    return a * b

result = multiply(4, 5)
print("Product:", result)

Output:

Product: 20

7. Variable Scope

  • Local Scope: Variables inside a function (accessible only within the function).
  • Global Scope: Variables outside a function (accessible everywhere).

Example:

x = 10  # Global variable

def modify_variable():
    global x  # Use global keyword to modify
    x = 20

modify_variable()
print("Value of x:", x)

Output:

Value of x: 20

8. Lambda Functions (Anonymous Functions)

A lambda function is a small, one-line function.

Syntax:

lambda parameters: expression

Example:

square = lambda x: x * x
print("Square:", square(4))

Output:

Square: 16

9. Practice Tasks for Day 6

Task 1: Simple Calculator

Write a function that performs addition, subtraction, multiplication, or division based on user input:

def calculator(a, b, operation):
    if operation == "add":
        return a + b
    elif operation == "subtract":
        return a - b
    elif operation == "multiply":
        return a * b
    elif operation == "divide":
        return a / b
    else:
        return "Invalid operation"

result = calculator(10, 5, "add")
print("Result:", result)

Task 2: Find Maximum of Three Numbers

Write a function that returns the largest of three numbers:

def find_max(a, b, c):
    return max(a, b, c)

print("Maximum:", find_max(10, 20, 15))

Task 3: Factorial of a Number

Write a function to calculate the factorial of a number:

def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

print("Factorial of 5:", factorial(5))

Task 4: Count Vowels in a String

Write a function to count the number of vowels in a string:

def count_vowels(text):
    vowels = "aeiouAEIOU"
    count = 0
    for char in text:
        if char in vowels:
            count += 1
    return count

print("Number of vowels:", count_vowels("Hello World"))

10. Common Mistakes to Avoid

  1. Not Calling the Function:
    Defining a function won’t execute it—you must call it.

    def say_hello():
        print("Hello!")
    
    say_hello()  # Correct
    
  2. Using Undefined Variables:
    Local variables inside a function cannot be accessed outside it.

  3. Mixing Return and Print:
    Use return when you need to pass the value back to the caller, not print.


11. Pro Tips for Day 6

  • Start using functions to organize your code into logical sections.
  • Always test your functions with various inputs.
  • Write clear and meaningful function names to make your code readable.

🎯 Day 6 Goal: Write at least 5 different functions that solve practical problems, such as basic calculations or string manipulations.

Let me know when you’re ready for Day 7! 🚀

Tags:

Post a Comment

0Comments

Post a Comment (0)