livepython.net
CHAPTER 15Python Functions
15.2  ARGUMENTS

Python Function Parameters and Arguments

Parameters and Arguments in Python

A parameter is a name in the brackets of a def: a variable that waits for a value. An argument is the value you put in the brackets when you call the function.

Think of it like a form with a blank: "Hello, ____!" The blank is the parameter. What you write in it is the argument.

PYTHONedit me
def greet(name):
    print(f"Hello, {name}!")

greet("Sunny")
greet("Rocky")
OUTPUT
Hello, Sunny!
Hello, Rocky!

One function, two different greetings. The argument changes, the function stays the same.

In the defIn the call
the parameter namethe argument "Sunny"
a blank to fill inthe value that fills it

The rules

  • When you call greet("Sunny"), Python does name = "Sunny" at the start of the body.
  • An argument can be any value: a string, a number, a list, or a variable.
  • The parameter only exists inside the function (more on that in topic 4).
  • You met this idea in chapter 2: sep and end are parameters of print().

The argument can come from a variable, even one with a different name, or from input():

PYTHONedit me
def greet(name):
    print(f"Hello, {name}!")

user = input()
greet(user)
OUTPUT
Hello, Lucky!

Avoid: leaving out the argument

PYTHONedit me
def greet(name):
    print(f"Hello, {name}!")

greet()
OUTPUT
TypeError: greet() missing 1 required positional argument: 'name'

Don't be scared of this error! It's saying: greet() needs a value for name, and you didn't give one. Put the value in the brackets.

Parameters are the blanks in the def; arguments are the values you fill in when you call.

your turnPredict the output

What will this print?

def double(n): print(n * 2) double(5) double("ab")
Your turn! What will this code show on the screen?
your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

More Than One Parameter: Order Matters

A function can have several parameters, separated by commas. When you call it, the arguments are matched to the parameters by position: the first argument goes to the first parameter, the second to the second. These are called positional arguments.

Think of it like seats in a cinema: ticket 1 goes to seat 1, ticket 2 to seat 2. Swap the tickets, and people sit in the wrong seats.

PYTHONedit me
def introduce(name, age):
    print(f"{name} is {age} years old.")

introduce("Sunny", 25)
introduce(25, "Sunny")
OUTPUT
Sunny is 25 years old.
25 is Sunny years old.

The second call has no error, but the sentence is nonsense. Python doesn't check what makes sense: it only matches by position.

The rules

  • Write as many parameters as you need, with a comma between them.
  • Call with the same number of arguments, in the same order.
  • Pick clear parameter names, so the order is easy to remember: price, quantity beats a, b.
PYTHONedit me
def show_total(price, quantity):
    print("Total:", price * quantity)

show_total(40, 3)
show_total(12.5, 4)
OUTPUT
Total: 120
Total: 50.0

Avoid: too many or too few arguments

PYTHONedit me
def introduce(name, age):
    print(f"{name} is {age} years old.")

introduce("Sunny", 25, "Pune")
OUTPUT
TypeError: introduce() takes 2 positional arguments but 3 were given

Every error is a clue! This one counts for you: 2 parameters, 3 arguments. Give one argument too few, and you get the "missing 1 required positional argument" error from the last lesson.

Common beginner doubt: "Will Python notice if I swap a name and a number?" No. Python happily puts any value in any parameter. Only an error later, or a strange output, will tell you. That's why the next lesson's keyword arguments are so handy.

Arguments fill the parameters in order: same number, same order.

your turnFill the gap

Call area() so it prints 20

def area(length, width): print(length * width) area(4? 5)

It should print: 20

Which piece makes this code work?
your turnPredict the output

What will this print?

def minus(a, b): print(a - b) minus(3, 10)
Your turn! What will this code show on the screen?

Keyword Arguments in Python

A keyword argument is an argument with its parameter's name in front: age=25. Python matches it by name, not by position. You've used these since chapter 2: print("a", "b", sep="-").

Think of it like a name tag on your luggage: whatever order the bags come out in, each one reaches the right person.

PYTHONedit me
def introduce(name, age):
    print(f"{name} is {age} years old.")

introduce(age=25, name="Sunny")
introduce("Rocky", age=30)
OUTPUT
Sunny is 25 years old.
Rocky is 30 years old.

The rules

  • Write parameter=value in the call. No spaces around the = is the usual style.
  • The order of keyword arguments doesn't matter.
  • The names must match the parameter names exactly.
  • You can mix both kinds: positional first, then keyword.

Why use them?

Compare these two calls of the same function:

book_ticket("Sunny", 2, True)
book_ticket(name="Sunny", seats=2, window=True)

The second one explains itself: you don't need to look up what 2 and True mean.

Avoid: a positional argument after a keyword one

PYTHONedit me
def introduce(name, age):
    print(f"{name} is {age} years old.")

introduce(name="Sunny", 25)
OUTPUT
SyntaxError: positional argument follows keyword argument

Once you start using names, keep using them to the end of the call.

Avoid: a misspelt name

PYTHONedit me
def introduce(name, age):
    print(f"{name} is {age} years old.")

introduce(nam="Sunny", age=25)
OUTPUT
TypeError: introduce() got an unexpected keyword argument 'nam'. Did you mean 'name'?

Python even suggests the right name.

Keyword arguments match by name, so their order doesn't matter. Positional ones go first.

your turnPick the right idea

Which call of introduce(name, age) is NOT allowed?

Think about it, then pick one.
your turnFix the code

Fix the call so it prints: 2 x tea

It should print: 2 x tea

def order(item, qty):
    print(qty, "x", item)

order(item="tea", 2)
This code does not work yet. Fix it, then press Run.

Default Parameter Values

A default value is the value a parameter gets when the call leaves it out. You write it in the def with an = sign: def greet(name, greeting="Hello"):.

Think of it like ordering tea: unless you say otherwise, it comes with one spoon of sugar. Ask for three, and you get three.

PYTHONedit me
def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Sunny")
greet("Rocky", "Good morning")
greet("Lucky", greeting="Hi")
OUTPUT
Hello, Sunny!
Good morning, Rocky!
Hi, Lucky!

The rules

  • A parameter with a default is optional: leave it out, and the default is used.
  • Give an argument, and it replaces the default for that call.
  • Parameters with defaults go after the ones without.
  • You've used defaults all along: print() has end="\n", which is why it starts a new line unless you say otherwise (chapter 2).

A default is great for a value that's nearly always the same:

PYTHONedit me
def power(base, exponent=2):
    print(base ** exponent)

power(5)
power(2, 10)
OUTPUT
25
1024

Avoid: a default before a parameter without one

PYTHONedit me
def greet(greeting="Hello", name):
    print(f"{greeting}, {name}!")
OUTPUT
SyntaxError: parameter without a default follows parameter with a default

It's saying the order is wrong. If greeting were optional but came first, Python couldn't tell which argument is which in greet("Sunny"). Move the defaults to the end.

Common beginner doubt: "Can every parameter have a default?" Yes. Then you can call the function with no arguments at all, and every default is used.

A default value makes a parameter optional. Put parameters with defaults last.

your turnPredict the output

What will this print?

def tea(sugar=1): print("Sugar:", sugar) tea() tea(3)
Your turn! What will this code show on the screen?
your turnType the output

Remember the string methods?

name = " sunny " print(name.strip().title())
Read the code line by line, then type the output exactly.

Practice: Arguments

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 132.Python Program to Find the Area and Perimeter Using a FunctionEasySolve
  2. 133.Python Program to Calculate a Bill with a Default TipMediumSolve
  3. 134.Python Program to Print a Triangle Using a Function with ParametersMediumSolve