Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
** Default and Keyword Arguments in Python Functions**
Python is widely praised for its clean syntax and flexibility, especially when it comes to defining functions. Among the key features that make Python functions powerful are default arguments and keyword arguments. These tools allow you to create more versatile and user-friendly functions, eliminating redundancy and enhancing readability.
In this guide, weโll break down these concepts in a beginner-friendly way, walk through real-world examples, and explore best practices.
๐ง Why Are Default and Keyword Arguments Important?
When writing functions, there are times you want to give the user the option to skip some arguments without causing an error. Or perhaps you want to make sure arguments are provided in a clear and self-explanatory way. Thatโs where default and keyword arguments shine.
They help with:
- โ Simplifying function calls
- โ Avoiding repetition
- โ Making functions more intuitive
- โ Reducing bugs due to incorrect argument order
โ Prerequisites
Before jumping in, you should be familiar with:
- Writing basic Python functions using
def
- Calling functions with positional arguments
- Basic data types like strings, numbers, and lists
๐ง Default Arguments in Python
A default argument is a function parameter that assumes a default value if no value is provided in the function call.
โ Syntax:
def greet(name="Guest"):
print(f"Hello, {name}!")
โ Example:
greet() # Output: Hello, Guest!
greet("Alice") # Output: Hello, Alice!
In this case, if the user doesnโt supply a name, the function defaults to โGuestโ.
๐ฏ Why use default arguments?
- They reduce the need to repeat common values.
- They allow optional customization.
- They prevent function call errors due to missing parameters.
๐ Keyword Arguments in Python
Keyword arguments allow you to call a function by specifying the parameter names explicitly, instead of relying solely on the position.
โ Syntax:
def describe_pet(animal, name):
print(f"{name} is a {animal}")
โ Example:
describe_pet(animal="dog", name="Buddy") # Output: Buddy is a dog
describe_pet(name="Whiskers", animal="cat") # Output: Whiskers is a cat
Notice that you can change the order when using keyword arguments. This increases clarity, especially when functions have many parameters.
๐ Combining Positional, Default, and Keyword Arguments
Python lets you mix these types of arguments in one function, but there are rules.
โ Valid Order:
def example(positional, default_value="Default"):
pass
โ Example:
def book_ticket(destination, seat="Window"):
print(f"Booking seat: {seat} to {destination}")
book_ticket("Paris") # Output: Booking seat: Window to Paris
book_ticket("Rome", "Aisle") # Output: Booking seat: Aisle to Rome
You can also use keyword arguments to make the call more readable:
book_ticket(destination="London", seat="Middle")
โ ๏ธ Important Rules to Remember
- Default arguments must follow non-default arguments:
# โ Invalid:
def greet(name="Guest", message):
pass
# โ
Valid:
def greet(message, name="Guest"):
pass
- Do not use mutable types (like lists) as default values:
# โ Dangerous:
def add_item(item, item_list=[]):
item_list.append(item)
return item_list
# โ
Safe:
def add_item(item, item_list=None):
if item_list is None:
item_list = []
item_list.append(item)
return item_list
- Mixing positional and keyword arguments:
- Positional arguments must come before keyword arguments when calling a function.
# โ
Valid
greet("Alice", message="Hi")
# โ Invalid
greet(message="Hi", "Alice") # SyntaxError
๐งช Real-World Examples
1. Sending Emails with Optional Subjects
def send_email(to, subject="No Subject"):
print(f"Sending email to {to} with subject: {subject}")
send_email("john@example.com")
send_email("sara@example.com", "Meeting Reminder")
2. Logging Messages with Optional Severity
def log(message, level="INFO"):
print(f"[{level}] {message}")
log("System started")
log("Disk space low", level="WARNING")
3. Building a Profile with Defaults
def create_profile(name, country="USA"):
return {"name": name, "country": country}
print(create_profile("Alice"))
print(create_profile("Tom", country="UK"))
4. Creating Flexible Greeting Messages
def greet_user(greeting="Hello", name="Guest"):
print(f"{greeting}, {name}!")
greet_user()
greet_user("Hi")
greet_user(name="Emily")
greet_user(greeting="Welcome", name="David")
5. Generating Reports with Optional Filters
def generate_report(title, year=None, author="Admin"):
print(f"Report: {title}")
if year:
print(f"Year: {year}")
print(f"Author: {author}")
generate_report("Sales Summary")
generate_report("Inventory", year=2023)
๐ก Best Practices
- Use default arguments when parameters are optional.
- Use keyword arguments to enhance code readability.
- Avoid mutable default values like lists or dictionaries.
- Clearly document the function and explain defaults if needed.
- Consider default arguments as a way to provide safe fallbacks.
๐ซ Common Mistakes
- Placing default arguments before non-defaults
- Using mutable default values
- Assuming keyword arguments will always be passed in the same order
Default and keyword arguments make Python functions powerful, flexible, and easy to work with. Whether youโre building user interfaces, handling configurations, or simplifying everyday tasks, mastering these features will make your code more efficient and professional.
By understanding how to use them correctly, youโll write functions that are easier to read, maintain, and extend โ a hallmark of great Python development.