Appearance
Defining Function
With Return
cmd
int add() {
int a = 20;
int b = 40;
int c = a + b
return c;
}python
def add():
a = 20
b = 40
c = a + b
return c- return_type: The data type of the value the function will return (e.g., int, float, void for no return).
- function_name: The name of the function.
- parameters: The input variables or arguments passed to the function (optional).
Without Return
cmd
void greeting() {
printf("Hi there!\n");
}python
def greeting():
print("Hi there!")- Without return means when the function is called, it won’t return any value. Instead, it will only execute the commands inside. For example: printing a sentence.
Example
Without Parameter
cmd
void greet() {
// in C
printf("Hello, welcome!\n");
// in C++
std::cout << "Hello, welcome!" << std::endl;
// in Java
System.out.println("Hello, welcome!");
}
int main() {
// Calling the function
greet(); // Function call
return 0;
}python
def greet():
print("Hello, welcome!")
greet()Output:
"Hello, welcome"
Note:
- In
CandC++, the functions need to be defined b__efore the main function__. - In
Java, it's not necessary to define the functions before the main function. - Since
Pythonis an interpreted language, there's no need for a separate main() function. The script is executed sequentially, and code outside functions is executed when the script is run. Therefore, the greet() function is called directly.
With Parameter
cmd
int addNumbers(int a, int b) {
int sum = a + b;
return sum;
}
int main() {
int num1 = 5;
int num2 = 3;
int result = addNumbers(num1, num2);
printf("The sum of %d and %d is: %d\n", num1, num2, result);
return 0;
}python
def add_numbers(a, b):
sum = a + b
return sum
num1 = 5
num2 = 3
result = add_numbers(num1, num2)
print(f"The sum of {num1} and {num2} is: {result}")Output:
“The sum of 5 and 3 is: 8”
Note:
- In
Python, the script is executed sequentially, and code outside functions is run when the script is executed. Therefore, you can directly call the function without encapsulating the logic within a specific main function.
Challenge:
- try to print the sum variable inside the main function, can you see the output? C / C++ / Java
- try to print the sum variable outside of the add_numbers() function, can you see the output ? Python