Functions and Different Types of Function Parameters in Python

🌟 Background & Passion:
With a background in Data Science and Natural Language Processing, I've always been fascinated by the power of programming to solve real-world problems. My journey into the world of Python began in college days when I first took a course in Python. Ever since, I've been passionately exploring the endless possibilities that Python offers.
🔍 What I Do:
By day, I'm a freelance Data Scientist. By night, I turn into a Python explorer, delving into new libraries, and frameworks, and constantly updating my blog to share my learnings and experiences.
✍️ My Blog's Mission:
Code and Query is more than just a blog; it's a platform where I aim to simplify Python programming and Data Science/Machine Learning concepts for beginners and enthusiasts alike. From basic concepts to advanced techniques, I strive to make my posts as clear, comprehensive, and engaging as possible. My goal is to help you not just understand data, but also appreciate its elegance and efficiency and derive trends and insights.
🌐 Beyond Python:
When I'm not coding or writing, you'll find me writing poetries or reading philosophy. I believe in a balanced life, where passions outside of work fuel creativity and new ideas within my professional sphere.
💬 Let's Connect:
I love connecting with fellow Python enthusiasts and tech lovers. Feel free to reach out to me on kritishapanda75@gmail.com or other social media handles on my profile. Whether it’s feedback, ideas, or just a chat about technology, I'm all ears!
In Python, functions are a fundamental building block that allow you to write reusable and organized code. Understanding how to define functions and use different types of parameters is crucial for writing effective Python programs.
What is a Function?
A function in Python is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
Defining a Function
Functions are defined using the def keyword, followed by the function name and parentheses (which may include parameters).
Example:
def greet(name):
print(f"Hello, {name}!")
Types of Function Parameters
Positional Parameters: These are the most common parameters. The arguments passed to the function are in order and are matched positionally.
def add(a, b): return a + bKeyword Arguments: When calling functions, you can specify arguments by the names of their corresponding parameters.
result = add(b=10, a=20) # Keyword argumentsDefault Parameters: You can provide default values to parameters. If no argument is provided, the default value is used.
def greet(name, message="Good morning!"): print(f"Hello, {name}, {message}")Variable-length Arguments:
Arbitrary Positional Arguments (
*args): Allows you to pass a variable number of arguments. Inside the function, it behaves as a tuple.def sum_all(*args): return sum(args)Arbitrary Keyword Arguments (
**kwargs): Allows for passing a variable number of keyword arguments. Inside the function, it behaves like a dictionary.def config(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}")
Let's understand keyword arguments with an example:
def print_user_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
# Calling the function with keyword arguments
print_user_info(name="Alice", age=30, occupation="Data Scientist", location="New York")
# Output:
# name: Alice
# age: 30
# occupation: Data Scientist
# location: New York
Check out this amazing video for a quick recap of the concepts you've learnt so far
Understanding Map, Reduce, and Filter in Python
Python offers several built-in functions that allow for efficient and concise data processing: map, reduce, and filter. These functions embody the functional programming style, often leading to more readable and efficient code.
Map Function
The map function applies a given function to each item of an iterable (like a list) and returns a map object (which is an iterator).
Example:
def square(number):
return number ** 2
numbers = [1, 2, 3, 4, 5]
squared = map(square, numbers)
print(list(squared))
# Output: [1, 4, 9, 16, 25]
Reduce Function
The reduce function, part of the functools module, is used for applying a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. This function is different from map and filter as it does not return a new list based on the function and iterable we've passed. Instead, it returns a single value.
Example:
from functools import reduce
def add(x, y):
return x + y
numbers = [1, 2, 3, 4, 5]
result = reduce(add, numbers)
print(result)
# Output: 15
Filter Function
The filter function constructs an iterator from elements of an iterable for which a function returns true.
Example:
def is_even(number):
return number % 2 == 0
numbers = [1, 2, 3, 4, 5]
filtered_numbers = filter(is_even, numbers)
print(list(filtered_numbers))
# Output: [2, 4]
map, reduce, and filter are powerful functions that facilitate a functional approach to Python programming. They allow for clean, efficient, and often more readable code when dealing with collections of data. Understanding and utilizing these functions can significantly enhance your data processing capabilities in Python.
Understanding and using different types of function parameters in Python enhances the flexibility and power of your functions. Positional, keyword, default, and variable-length arguments allow you to handle various scenarios in function calls, making your code more adaptable and elegant. As you gain experience, these concepts will be invaluable tools in your Python programming toolkit.
Here’s a self check that really covers everything so far. You may have heard of the infinite monkey theorem? The theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type a given text, such as the complete works of William Shakespeare. Well, suppose we replace a monkey with a Python function. How long do you think it would take for a Python function to generate just one sentence of Shakespeare? The sentence we’ll shoot for is: “methinks it is like a weasel” You’re not going to want to run this one in the browser, so fire up your favorite Python IDE. The way we’ll simulate this is to write a function that generates a string that is 28 characters long by choosing random letters from the 26 letters in the alphabet plus the space. We’ll write another function that will score each generated string by comparing the randomly generated string to the goal. A third function will repeatedly call generate and score, then if 100% of the letters are correct we are done. If the letters are not correct then we will generate a whole new string. To make it easier to follow your program’s progress this third function should print out the best string generated so far and its score every 1000 tries.
Did you get the solution? No worries, here it is for you:
import random
def generate_string(length):
# Function to generate a random string of given length
characters = 'abcdefghijklmnopqrstuvwxyz '
return ''.join(random.choice(characters) for _ in range(length))
def score_string(random_string, target_string):
# Function to score the generated string
score = sum(r == t for r, t in zip(random_string, target_string))
return score / len(target_string)
def main(target_string):
best_score = 0
best_string = ''
attempt = 0
while best_score < 1:
attempt += 1
random_string = generate_string(len(target_string))
current_score = score_string(random_string, target_string)
if current_score > best_score:
best_score = current_score
best_string = random_string
print(f'Attempt {attempt}: {best_string} with score {best_score}')
if attempt % 1000 == 0:
print(f'After {attempt} attempts, best string: {best_string} with score {best_score}')
if best_score == 1:
print(f'Perfect match found after {attempt} attempts: {best_string}')
break
# The target Shakespearean sentence
target = "methinks it is like a weasel"
main(target)
See you in my next article on OOP in Python. Till then...

