Function Arguments and Return Values
Functions often need inputs to work with. These inputs are called arguments. You can also make functions return values, which you can reuse elsewhere.
Let’s break this down step by step.
1. Positional Arguments
These are the most common. You pass values in the order the function expects them.
def multiply(x, y): print("Product:", x * y) multiply(2, 4)
Explanation:
x
gets2
,y
gets4
- The result printed is
Product: 8
2. Return Values
Instead of just printing, functions can send a value back using return
.
def multiply(x, y): return x * y result = multiply(2, 4) print("Result:", result)
Explanation:
- The function calculates the product and returns it.
- We store the result in a variable and print it later.
3. Keyword Arguments
You can also pass values by name, which is more flexible.
def introduce(name, age): print(name, "is", age, "years old.") introduce(age=12, name="Liam")
Explanation:
- You don’t have to follow order if you use names.
- This improves clarity and avoids mistakes.
4. Default Values
Set a default value in the function definition to make arguments optional.
def greet(name="friend"): print("Hello,", name) greet() greet("Sophie")
Explanation:
- The first call uses the default ("friend").
- The second call overrides it with "Sophie"
Summary
Concept | Description |
---|---|
Positional arguments | Passed in order; e.g., func(2, 3) |
Keyword arguments | Passed by name; e.g., func(x=2, y=3) |
Default arguments | Optional values in the function definition |
return | Sends a value back to the caller |
What’s Next?
In the next lesson, we’ll explore variable scope and see what happens when functions are defined inside other functions.
Quiz
0 / 1
Understanding Function Arguments
When using arguments, the values are passed in the exact order the function expects them.
positional
keyword
default
anonymous
학습 자료
AI 튜터
디자인
업로드
수업 노트
즐겨찾기
도움말
코드 에디터
코드 실행
코드 생성
실행 결과