๐ฐ Introduction :

As your program grows, you’ll start to notice a lot of duplication. Instead of repeating the same code over and over, it’s better to compile it into a function that you can call when needed.
โ What is a Function ?
A function is a piece of code that performs a specific task and can be called multiple times.
Think of it like a “mini-program” within your program.
๐ฆ Creating a Simple Function :
โ General Syntax :
python
def function_name():
# Function Code
๐งช Example :
python
def say_hello():
print(“Welcome to the world of programming!”)
To run it:
python
say_hello()
๐ Functions with Parameters
You can send information to the function for it to operate on.
python
def greet(name):
print(“Hello, ” + name + “!)
greet(“Ali”)
greet(“Sara”)
๐ “Ali” and “Sara” are values sent to the function as parameters.
๐ Using return to return a result :
Python
def square(number):
return number * number
result = square(4)
print(“Result:”, result) # Result: 16
๐ return returns a result that can be stored or used later.
๐งฎ Practical Example :
A Function to Calculate the Area of a Rectangle:
Python
def area(width, height):
return width * height
w = float(input(“Enter width: “))
h = float(input(“Enter height: “))
print(“Area:”, area(w, h))
๐ Multiple Functions in One Program :
Python
def welcome():
print(“Welcome!”)
def add(x, y):
return x + y
welcome()
result = add(5, 3)
print(“5 + 3 =”, result)
โ ๏ธ Notes for Beginners:
It is preferable to give functions clear names that express their function.
Don’t forget to include parentheses () even when there are no parameters.
The code inside the function must be indented.
๐ง Exercise 1 :
Write a function that adds two numbers:
python
def sum_two(a, b):
return a + b
๐ง Exercise 2:
Write a function that checks if a number is even:
python
def is_even(n):
return n % 2 == 0
And use it like this:
python
number = int(input(“Enter a number: “))
if is_even(number):
print(“The number is even.”)
else:
print(“The number is odd.”)
๐ Conclusion :
Functions help you organize your code.
You can pass parameters and return results using return.
The more organized your code is, the more maintainable and extensible it is.
๐ What will we learn in Lesson 6 ?
In the sixth and final lesson of this series, we will create a simple software project: an interactive calculator using everything you have learned about variables, conditions, loops, and functions
โฌ๏ธ Download ZEQMA ุชุญู ูู