Functions in Python

A function in Python is a block of code that performs a specific task and returns a result. Functions help break down a program into smaller, more manageable pieces and make the code easier to read, test, and maintain. Functions define using the def keyword, followed by the name of the function, a set of parentheses, and a colon. The code within the function indent under the definition and execute when the function can call.

def func_name (optional_arguments)

statement

return optional_value

 

  • Arguments: Functions accept arguments, which values pass to the function when it calls and it specify in the parentheses of the function definition, however it use within the function to perform the desire task.
  • Return statement: Functions can return a result to the caller using the return statement for any data type, including numbers, strings, lists, dictionaries, etc. If a function doesn’t return a value, it returns None by default.
  • Scope: Variables can define inside a function are local to that function, it is not accessible outside of it. Variables define outside of a function can call global variables and can access from anywhere in the program.
  • Recursion: Functions can call themselves; this technique is recursion. Recursive functions are useful for solving problems that can break down into smaller, similar subproblems.
  • Default arguments: These arguments are used in the function definition but if a value doesn’t provide for a default argument, the default value will be used.
  • Keyword arguments: Functions can call using keyword arguments, which specify as key=value pairs but Keyword arguments allow you to specify arguments in any order if the names of the arguments can be provided.

Functions are a fundamental building block of Python programming and are essential for writing clean, reusable, and maintainable code.

Example:
def exp(i) :
return i*100
>>> exp(5)                       result = 500
In this case, when we recall exp with any number, the result is number*100

def exp(i) :

if i %2 ==0:

return ‘Pair’

return ‘Odd’

>>> exp(5)                       result = Odd

>>> exp(10)                     result = Pair

 

let’s to see video from our YouTube channel

 

If you want to learn more Python, please click here.

Share :
348
keyboard_arrow_up