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:Using the function with only required argument:Using the function with both arguments:You can have multiple arguments with default values:Important Rule: Default arguments must come after non-default arguments in the function definition.
def greet(name, greeting="Hello"):
print(name, greeting)greet("John")
# Output: John Hellogreet("john", "welcome")
# Output: john welcomedef 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 defaults# 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