← Python from Scratch
Lesson 45 of 78 · 10 XP
Function arguments
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Parameters can have default values. Then the argument can be left out:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Anya") # 'Hello, Anya!'
greet("Anya", "Salem") # 'Salem, Anya!' — "Salem" is Kazakh for hello
greet("Anya", greeting="Hi") # a keyword argument — clearer
Parameters with default values are written after ordinary ones.
*args takes any number of positional arguments as a tuple, and **kwargs takes keyword arguments as a dictionary:
def total(*nums):
return sum(nums)
total(1, 2, 3) # 6
Sometimes you need a function "just once" — for that there's the short lambda form:
words = ["banana", "apple", "kiwi"]
sorted(words, key=lambda w: len(w)) # ['kiwi', 'apple', 'banana']
Task. Write a function greet(name, greeting="Hello") that returns a string like Hello, Anya!. The check will call it in different ways, including with a keyword argument.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.