Default Values
Part of the Fundamentals section of Coddy's Python journey — lesson 48 of 77.
Sometimes when we create a function, we want to have some arguments that are optional, with predetermined default values.
Example:
def greet(name, greeting="Hello"):
print(name, greeting)Using the function with only required argument:
greet("John")
# Output: John HelloUsing the function with both arguments:
greet("john", "welcome")
# Output: john welcomeYou can have multiple default arguments:
def describe_person(name, age=25, city="Unknown"):
print(f"{name} is {age} years old and lives in {city}")describe_person("Alice")
# Uses both defaults
describe_person("Bob", 30)
# Uses default city
describe_person("Charlie", 35, "New York")
# Uses no defaultsImportant Rule: Default arguments must come after non-default arguments in the function definition.
# Correct: def greet(name, greeting="Hello"): print(f"{greeting}, {name}!")# Incorrect: def greet(greeting="Hello", name): print(f"{greeting}, {name}!")
Cheat sheet
Default arguments in functions:
def greet(name, greeting="Hello"):
print(name, greeting)
greet("John") # Output: John Hello
greet("John", "Welcome") # Output: John WelcomeMultiple default arguments:
def describe_person(name, age=25, city="Unknown"):
print(f"{name} is {age} years old and lives in {city}")
describe_person("Alice") # Uses both defaults
describe_person("Bob", 30) # Uses default city
describe_person("Charlie", 35, "New York") # Uses no defaultsImportant: Default arguments must come after non-default arguments in the function definition.
# Correct:
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
# Incorrect:
def greet(greeting="Hello", name):
print(f"{greeting}, {name}!")Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2