It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Parameters and Default Values

You’ll learn how to define functions with parameters and give those parameters default values so that the function can still run even when no argument is provided.


Function Parameters Refresher

A parameter is a variable that a function accepts as input. When you call the function, you pass in an argument (the actual value).

def greet(name):
    print("Hello", name)

greet("Kofi")  # Output: Hello Kofi

Using Default Values

Sometimes you want a function to run even when no argument is passed. You can assign default values to parameters.

def greet(name="Stranger"):
    print("Hello", name)

greet("Ama")        # Output: Hello Ama
greet()             # Output: Hello Stranger

This is useful when:

  • You want to provide a fallback value.
  • You want your function to be more flexible.

Real-World Example

Let’s say you're building a product info display. If no price is entered, it defaults to 0.

Multiple Parameters with Defaults

You can mix parameters with and without defaults. Just remember: non-default parameters must come first!

def describe_pet(animal, name="Unknown"):
    print(f"This is a {animal} named {name}.")

describe_pet("cat", "Whiskers")
describe_pet("dog")

Works fine

?describe_pet(name="Buddy", animal="dog") also works, because we’re using keyword arguments.

Exercise: Try It Yourself!

  1. Create a function welcome(name="Guest") that prints Welcome, <name>!.
  2. Write a function order_item(item="Bread", quantity=1) that prints something like: You ordered 1 Bread(s).
  3. Build a function say_goodbye(name="friend", language="English"):

    • If language is English, print Goodbye <name>!
    • If language is French, print Au revoir <name>!
    • Test it with and without arguments.

Summary

  • Parameters are values your function needs to work.
  • You can assign default values to make functions flexible.
  • Always place default parameters after the required ones.