Functions in Python

Introducing functions in Python
Functions are one of the most important concepts in programming that allow us to organize and manage our code. In this session, we will learn the basics of functions in Python and learn how to define and use our own functions.

Why functions?
You help us to:

  • Keep your code neat and readable: By breaking code into smaller, manageable chunks, we can better organize your code.
  • Reduce duplicate code: By defining a function to do a specific task, we can avoid code duplication.
  • Test and debug your code: By separating different parts of the code, we can find and fix problems more easily.

Defining a function in Python

To define functions in Python, we use the def keyword. The general structure of a function definition is as follows:

kpنحوه نوشتن توابع در پایتون
How to write functions in Python

Example

Let’s define a simple function called greet that takes a name as input and prints a welcome message:

تعریف تابع greet در پایتون
Definition of greet function in Python

 

Now we can use this function by calling it and giving it a name as input:

فراخوانی تابع greet در پایتون
Calling the greet function in Python

 

The output will look like this:

نتیجه استفاده از تابع greet
The result of using the greet function

Parameters and arguments

Functions can have parameters that are given as input to the function. In the example above, name is a parameter. When we call the function, the values ​​we pass to the parameters are called arguments.

Default parameters

We can define default values ​​for parameters. If no argument is given for those parameters, the default value is used:

نوشتن تابع با پارامتر پیشفرض
Write function with default parameter

 

Now if we call the function with no arguments, the default value is used:

نتیجه استفاده از تابع پیشفرض بدون آرگومان
The result of using the default function with no arguments

 

Return values ​​from functions

Functions can return values ​​as results. For this, we use the return keyword:

نحوه برگشت دادن یک مقدار از تابع
How to return a value from a function

 

The answer will be as follows:

نتیجه کد
The result of the code

 

Recursive functions

Recursive functions are functions that call themselves. These types of functions are useful for solving recursive problems such as calculating factorials or the Fibonacci sequence.

Example:

Factorial Let’s define a return function to calculate the factorial:

نوشتن تابع برای محاسبه فاکتوریل
Write a function to calculate the factorial

The answer will be as follows:

پاسخ تابع فاکتوریل برای عدد 5
The answer of the factorial function for the number 5

conclusion

In this session, we learned about the basics of functions in Python. We learned how to define functions, handle parameters and arguments, return values, and write recursive functions.