Python for Beginners begunpro

Python Learning Day 17-18

Python

Welcome to the next stage of your Python learning journey! Today, we’ll explore advanced aspects of functions—default arguments for added flexibility and docstrings for improved documentation.

Default Arguments

In Python, you can set default values for function parameters. This means that if a user doesn’t provide a value for a parameter, the default value will be used. Let’s take a look:

				
					# Example: Function with default argument
def greet(name="Guest"):
    print(f"Hello, {name}! Welcome!")

# Calling the function without providing a name
greet()  # Output: Hello, Guest! Welcome!

# Calling the function with a custom name
greet("Imran Khan")  # Output: Hello, Imran Khan! Welcome!

				
			

In this example, the name parameter has a default value of “Guest,” but you can still provide a different value when calling the function.

Docstrings

Docstrings are a way to document your functions, describing what they do, what parameters they take, and what they return. It’s a good practice for writing clear and readable code. Here’s an example:

				
					# Example: Function with docstring
def multiply(a, b):
    """
    This function multiplies two numbers.

    Parameters:
    a (int): The first number.
    b (int): The second number.

    Returns:
    int: The product of a and b.
    """
    result = a * b
    return result

				
			

You can access the docstring of a function using the help() function or by checking the .__doc__ attribute:

				
					help(multiply)
# or
print(multiply.__doc__)

				
			

Exercise: Advanced Greeting Function

Let’s create a more advanced greeting function. This function should take a name, an optional age with a default of 25, and an optional greeting message. It should then print a customized greeting.

				
					# Exercise: Advanced Greeting Function
def advanced_greet(name, age=25, greeting="Hello"):
    """
    This function generates a customized greeting.

    Parameters:
    name (str): The name of the person.
    age (int, optional): The age of the person (default is 25).
    greeting (str, optional): The greeting message (default is "Hello").
    """
    print(f"{greeting}, {name}! Age: {age}")

# Test the advanced_greet function
advanced_greet("Bob")  # Output: Hello, Bob! Age: 25
advanced_greet("Alice", 30)  # Output: Hello, Alice! Age: 30
advanced_greet("Charlie", greeting="Hi")  # Output: Hi, Charlie! Age: 25

				
			

Experiment with different combinations of parameters when calling the advanced_greet function.

Conclusion: Advancing Your Function Knowledge

You’ve now explored default arguments and docstrings, adding powerful tools to your Python toolkit. Default arguments provide flexibility, and docstrings enhance the readability and understanding of your code.

Keep practicing these concepts, and don’t forget to document your functions for yourself and others who may read your code. If you have any questions or want further clarification, feel free to ask.

As you continue your Python journey, consider subscribing to our newsletter for more tutorials and tips. Your dedication to learning is inspiring, and we’re excited to accompany you through more advanced Python topics. Happy coding!

Here are some exercises to reinforce your understanding of functions, default arguments, and docstrings. Feel free to experiment and modify them to deepen your learning:

Exercise 1: Temperature Converter Function

Write a Python function called convert_temperature that takes a temperature in Celsius and converts it to Fahrenheit. The function should have a default value of 0 for Celsius.

Exercise 2: File Reader Function

Create a function named read_file that takes a filename as a parameter and prints the contents of that file. If the file does not exist, the function should print an error message. Additionally, provide a docstring describing the purpose of the function.

Exercise 3: Sentence Reverser Function

Write a function called reverse_sentence that takes a sentence as a parameter and returns the sentence in reverse order. For example, if the input is “Hello World,” the function should return “World Hello.”

Exercise 4: Calculator with History

Enhance the calculator function from the previous exercise (Day 15-16) by adding a history feature. The function should store the results of each calculation in a list and print the history when requested.

Exercise 5: Password Generator Function

Create a function named generate_password that generates a random password of a specified length. The function should have a default length of 8 characters and include a mix of letters, numbers, and symbols.

Exercise 6: Palindrome Checker with Docstring

Build a function named is_palindrome that takes a word as a parameter and returns True if the word is a palindrome (reads the same backward as forward), and False otherwise. Include a detailed docstring explaining how the function works.

Exercise 7: List Filter Function

Write a function called filter_numbers that takes a list of numbers and returns a new list containing only the even numbers. Use a default argument for the filtering condition (e.g., even or odd).

Exercise 8: Word Counter Function

Create a function named count_words that takes a sentence as a parameter and returns a dictionary where the keys are unique words in the sentence, and the values are the frequency of each word.

Exercise 9: Unique Elements Function

Build a function named unique_elements that takes two lists as parameters and returns a new list containing only the unique elements from both lists.

Exercise 10: Fibonacci Printer

Write a function called print_fibonacci that takes a number n as a parameter and prints the first n terms of the Fibonacci sequence. Use a docstring to explain the purpose of the function.

Feel free to tackle these exercises at your own pace. They cover various aspects of functions and will provide a good opportunity to practice and solidify your understanding. If you have any questions or need assistance with any exercise, feel free to ask!