In Python, you can force a function to accept arguments by keyword-only. To do this, place an asterisk (*) before the keyword-only arguments in the function definition. This ensures that certain arguments must be passed as keywords, improving clarity and preventing errors.
print() Function
The print() function uses a keyword-only argument sep to specify the separator between printed values.
print("Hello", "World", sep="-") # Output: Hello-World
If you try to use sep as a non-keyword argument, it won’t work as intended:
print("Hello", "World", "-") # Output: Hello World -
In the following function, the rate argument is keyword-only. You must pass it as a keyword.
def intr(amt, *, rate):
val = amt * rate / 100
return val
interest = intr(1000, rate=10) # Correct usage
print(interest) # Output: 100.0
If you try to use rate as a positional argument, it will raise an error:
interest = intr(1000, 10) # Incorrect usage # TypeError: intr() takes 1 positional argument but 2 were given
🔹 Use * to enforce keyword-only arguments in your functions.
🔹 This ensures clarity and prevents accidental misuse of positional arguments.
