Computer ScienceChapter 3: Programming Fundamentals (Python)
3.11.2 Function Returns Result
A function is not always about displaying or printing.
Explanation level
A function is not always about displaying or printing. Functions are also used to solve an equation and return the result.
This is done by using the `return` keyword.
Example — Function that Returns a Value: ```python Lofnum = [7, 8, 9, 10, 11]
def listsumup(): sum = 0 for i in range(5): sum = sum + Lof_num[i] return (sum)
print(list_sumup()) ```
Output: ``` 45 ```
- `list_sumup()` defines a function that calculates the sum of all elements in a list
- `return (sum)` sends the result back to the caller
- `print(list_sumup())` calls the function and prints the returned value
Important Point: A function can return a single value only. A good practice is to enclose the variable or value in `()` after `return`.
Local vs Global Variables
| Feature | Local Variable | Global Variable |
|---|---|---|
| Defined | Inside a function | Outside all functions |
| Scope | Only inside the function | Throughout the program |
| Access | Can be accessed only inside the function | Can be accessed anywhere |
| Testing | Easy to test | Harder to test |
| Memory | Freed after the function ends | Stays as long as the program runs |
Example: ```python global_var = 10 # Global variable
def myfunction(): localvar = 20 # Local variable print("Global:", globalvar) print("Local:", localvar)
myfunction() print("Global outside:", globalvar) # print(local_var) # This would cause an error ```
Output: ``` Global: 10 Local: 20 Global outside: 10 ```
Intermediate Level
Why Functions Matter
As programs grow, functions help by:
- Breaking complex problems into smaller parts
- Avoiding repetition (write once, use many times)
- Making code readable (function names describe what they do)
- Making debugging easier (errors are localized)
- Enabling collaboration (different people can work on different functions)
Types of Functions
1. Functions without arguments and without return: ```python def say_hello(): print("Hello")
say_hello() # Hello ```
2. Functions with arguments but without return: ```python def greet(name): print("Hello,", name)
greet("Ali") # Hello, Ali ```
3. Functions without arguments but with return: ```python def get_pi(): return 3.14159
pi = getpi() print(pi) # 3.14159 ```
4. Functions with arguments and return: ```python def add(a, b): return a + b
result = add(5, 3) print(result) # 8 ```
Argument Types
Positional Arguments: Arguments passed in the order they are defined. ```python def greet(first, last): print("Hello,", first, last)
greet("Ali", "Khan") # Hello, Ali Khan ```
Keyword Arguments: Arguments passed with the parameter name. ```python greet(last="Khan", first="Ali") # Hello, Ali Khan ```
Default Arguments: Arguments with default values. ```python def greet(name="Guest"): print("Hello,", name)
greet() # Hello, Guest greet("Ali") # Hello, Ali ```
Return Values
A function can return a value using the `return` keyword.
Example: ```python def square(x): return x * x
result = square(5) print(result) # 25 ```
Multiple Return Values: Python allows returning multiple values as a tuple.
```python def min_max(nums): return min(nums), max(nums)
low, high = min_max([3, 1, 4, 1, 5, 9]) print(low, high) # 1 9 ```
Common Patterns with Functions
Pattern 1 — Calculate Area: ```python def areaofrectangle(length, width): return length * width
print(areaofrectangle(5, 3)) # 15 ```
Pattern 2 — Check Even or Odd: ```python def is_even(num): return num % 2 == 0
print(iseven(4)) # True print(iseven(7)) # False ```
Pattern 3 — Find Maximum: ```python def find_max(a, b, c): if a >= b and a >= c: return a elif b >= a and b >= c: return b else: return c
print(find_max(10, 25, 15)) # 25 ```
Formula / Mathematical Form
Not applicable for this topic.
Solved Example
Example — Function to Calculate Simple Interest
Given: - Principal amount, rate, and time
Required: - Calculate simple interest and return it
Formula: ``` Simple Interest = Principal × Rate × Time100 ```
Code: ```python def simple_interest(principal, rate, time): interest = principal * rate * time100 return interest
Call the function result = simple_interest(1000, 5, 2) print("Simple Interest:", result) ```
Output: ``` Simple Interest: 100.0 ```
- The function `simple_interest` takes three arguments: `principal`, `rate`, and `time`
- It calculates the interest using the formula
- It returns the result
- The result is stored in the variable `result` and printed
Important Points
- - A function is a named block of code that performs a specific task.
- - Functions are defined using the `def` keyword.
- - Functions are called by writing their name followed by parentheses.
- - Functions can take arguments (inputs).
- - Functions can return a result using the `return` keyword.
- - A function can return a single value only.
- - Variables defined inside a function are local to that function.
- - Variables defined outside all functions are global.
- - Local variables cannot be accessed outside the function.
- - Global variables can be accessed anywhere in the program.
- - Functions help divide a large program into smaller, manageable parts.
- - Functions improve reusability, readability, and maintainability of code.
Remember
- - Function = Named block of code that performs a specific task.
- - `def` = Keyword to define a function.
- - **0** = Call a function.
- - Arguments = Inputs to a function.
- - `return` = Sends a result back to the caller.
- - Local variable = Defined inside a function.
- - Global variable = Defined outside all functions.
- - A function can return only one value (but it can be a tuple).
- - Functions help organize large programs.
Common Mistakes
- - Forgetting to call a function: Defining a function does not execute it. You must call it.
- - Forgetting the colon (`:`): `def my_func()` without `:` causes an error.
- - Incorrect indentation: Code inside a function must be indented.
- - Confusing local and global variables: Local variables cannot be accessed outside the function.
- - Forgetting the `return` keyword: Without `return`, the function returns `None` by default.
- - Using a variable before defining it: Local variables must be assigned before use.
- - Passing arguments in the wrong order: Positional arguments must be in the same order as defined.
- - Thinking a function can return multiple values directly: A function returns a single value, but that value can be a tuple.
- - Modifying a global variable without the `global` keyword: This creates a new local variable instead of modifying the global one.
Quick Revision
As programs grow larger, it becomes hard to keep track of the logic, especially when multiple algorithms coexist. The solution is to divide the code into segments — each segment does a separate task and can be called upon to fulfill that particular task. Such segments are called functions.
In Python, `def` is used to define a function with a unique name, followed by `():`.
- Example:
- ```python
- def myfirstfunc():
- print('This line is printed, when myfirstfunc() is called')
- ```
The beauty of defining a function is that the same functionality can be achieved for different values. This is done by passing arguments to the function. The function needs to be defined in such a way that it accepts a value and stores it in a variable and uses it inside the function.
The variable defined inside the function does not exist outside the function and is called a local variable; its scope is limited to the function itself. Variables in the main program are called global variables.
A function is not always about displaying or printing. Functions are also used to solve an equation and return the result. This is done by using the `return` keyword.
A function can return a single value only. A good practice is to enclose the variable or value in `()` after `return`.
60-Second Revision
- Function = Named block of code that performs a specific task.
- **0** = Define a function.
- **0** = Call a function.
- Arguments = Inputs to a function.
- `return` = Sends result back to the caller.
- Local variable = Inside a function, not accessible outside.
- Global variable = Outside all functions, accessible everywhere.
- A function returns one value (but can be a tuple).
- Functions help organize large programs — divide, reuse, and maintain.
- Warning: Always call a function to execute it — defining alone does not run it.
Did you understand this topic?
Your answer is saved with your learning record. It does not mark the topic as mastered.
Quick revision
Revision Zone
Review the key facts, formulas and checks before you move on.3.11.2 Function Returns Result
Sticky Notes · Quick Revision
Key Point 1
- Function = Named block of code.
Key Point 2
- **0** = Define a function.
Key Point 3
- **0** = Call a function.
Key Point 4
- Arguments = Inputs to a function.
Key Point 5
- `return` = Sends result back.
Key Point 6
- Local variable = Inside a function.
Key Point 7
- Global variable = Outside all functions.
Key Point 8
- A function returns one value (but can be a tuple).
Key Point 9
- Functions help organize large programs.
Key Point 10
- `draw_line()` example: define once, call many times.
Same supplied content as this Notes page (shared canonical source).