Introduction

Setup

Operators

variable

String

Number

Dtype & Comment

Lists

Tuples

Sets

Dictionaries

if else statement

For Loop

While Loop

iterator & iterable

Pre-Built functions

Function

Decorators

generators

Types of errors

Exceptions Handling

OOP

Regular expression

Create module

OS module

Date module

Random module

Math

Statistics module

Exercise 1

Exercise 2

Exercise 3

Learn Data Structure & Algorithm

Learn Numpy

Learn Pandas

Learn Matplotlib

Learn Seaborn

Learn Statistics

Learn Math

Learn MATLAB

Learn Machine learning

Learn Github

Learn OpenCV

Learn Deep Learning

Learn MySQL

Learn MongoDB

Learn Web scraping

Learn Excel

Learn Power BI

Learn Tableau

Learn Docker

Learn Hadoop

Python function

What is function in python?

The function is a block of code. It only runs when we called it. We will pass data through parameters into a function and when we call the function it will return or print the data as a result. The facility of function is that we write the code one time and can use it how many times we want. We can also pass different parameter values while calling the function.

How to write functions in python?

First, write def then the function name then the first bracket, and then a colon. After this write the code inside it. At last call the function by the name. Call the function by going outside of the function. We can't give space between the function name words. But we can use a separator like a dash, hyphen, etc.

Example:1
Input
def my_function():
  print("Hello ")
my_function()
Output
Hello

In example 1, we created a function named my_function. Inside the function, we wrote a simple code, that is to print "Hello world". After that, go outside of the function and call the function by its name and after that, the function runs and we got the output "Hello world".

Example:2
Input
def my_function(pra):
  print(pra)
my_function("Rafsan")
my_function("Ahmad")
my_function("RafsanAhmad")
Output
Rafsan
Ahmad
RafsanAhmad

In example 2, we have a parameter in function which is pra and we called the function three times and each time we gave a different value to the function while calling the function. So when we gave value while calling the function, it means that we are giving value to the parameter. So when we gave value Rafsun it means we gave value to the parameter pra. So when pra got value Rafsun it runs the code with that value and gives us output Rafsun. In the same way, when we gave Ahmad and RafsanAhmad it takes the value runs the code, and gave us the output. Because we called the function three times so we got three outputs.

Example:3
Input
def my_function(a,b):
  print(a)
  print(b)
my_function("Self",1)
my_function("Taught",2)
my_function(3,"SelfTaught")
Output
Self
1
Taught
2
SelfTaught
3

In example 3 we used 2 parameters. We can use parameters how many we want. We can pass a number or string value to the parameter at a time. In the example, We can see that for a parameter we gave a string and for b we gave a number, and when we called we get two different values of two different parameters.

Example:4
Input
def my_function(a,b,c):
  print(a+" "+b+" "+c)
my_function(a="Self",b="Taught",c="No.1")
Output
Self Taught No.1
Example:5
Input
def my_function(a,b):
  print(a,b)
my_function("Self")
my_function("Taught")
my_function("SelfTaught")
Output
my_function() missing 1 required positional argument: 'b'

In example 5, we used 2 parameters but we pass one value so we will get an error. We have to give the same number of values according to the number of parameters.

Example:6
Input
def my_function(a,b="No_value"):
  print(a,b)
my_function("Self")
my_function("Taught")
my_function("SelfTaught",3)
Output
Self No_value
Taught No_value
SelfTaught 3

In example 6, we used 2 parameters but we pass one value so we will get an error. We have to pass the same number of values according to the number of parameters. If we forget to pass value and if we don't want to get an error, then we have to pass a default value for that parameter as we gave to the b parameter. To do this give equal and then write the default value in the double or single quotation. But if we want to give a default value to the parameter then we have to start giving the default value from the end and have to come to the start. We have to give value serially. If we give a default value to the first and third parameters and don't give it to the second parameter then it will give an error. We have to give value serially and can't escape one in the middle.

Example:7
Input
def(v):
  for i in z:
    b=v[i]
    print(b,end=" ")
z="7545345"
vv=v[::-1]
ve=(vv)
Output
What will be the output?
Example:8
Input
def my_func(v):
  y=0
  for i in range(v):
    z=input("Enter your value:")
    xyz=y+int(z)
  print(xyz)
x=int(input("Enter number:"))
my_func(x)
Output
Guess the output
Example:9
Input
def my_func(v):
  y=[]
  for i in range(v):
    z=input("Enter your value:")
    y.append(z)
  print(y)
x=int(input("Enter number:"))
my_func(x)
Output
Guess the output
Example:10
Input
def my_func(v):
  y=""
  for i in v:
    z=y+i
  print(z)
x=int(input("Enter name:"))
l1=list(x)
my_func(li)
Output
Guess the output
Example:11
Input
def sumnum(num):
  prenum=0
  for i in range(num):
     sum=prenum+1
     print("sum:",sum,"Previous number:",prenum,"Current number",i)
     prenum=i+1
sumnum(10) Output
Guess the output

*args

If we write a parameter and give an asterisk(*) sign before it then we can pass unlimited values through that parameter. Normally we can pass one value for one parameter. But we use the asterisk(*) sign before the parameter then we can pass unlimited values through that parameter.

Example:1
Input
ef my_function(*a):
  print(a)
my_function("Rafsan",1,2,3,"Ahmad",5,"RafsunAhmad")
Output
('Rafsan', 1, 2, 3, 'Ahmad', 5, 'RafsunAhmad')
Example:2
Input
def my_function(*a):
  print(a[4])
my_function("Rafsan",1,2,3,"Ahmad",5,"RafsunAhmad")
Output
Rafsan

**kwargs

If we don't know how many keyword arguments we have to pass into the function, then we should add two asterisks (**) signs before the parameter in the function definition. In this way the function will receive arguments as a dictionary and also the function will be able to access the items accordingly.

Example:
Input
def my_function(**name):
  print(" last name is " + name["last_name"])
  print(" first name is " + name["first_name"])
my_function(first_name = "Rafsun", last_name = "Ahmad")
Output
last name is Ahmad
First name is Rafsun

How to return a function in python?

We can return the output from a function.

Example:
Input
def function_name(a):
   return 5+a
print(function_name(2))
print(function_name(4))
Output
7
9

pass

Function definitions can't be empty. But if we have for some reason then put a pass statement to avoid getting an error.

Example:
Input
def function_name():
   pass
Output

How to write function inside function in python?

Example:1
Input
def outer_func():
  def inner_func():
    print(" I'm from inner_func")
  return def inner_func
var=outer_func()
var()
Output
I'm from inner_func

In example outer_func return inner_func.So it means now var variable has inner_func. So when we called var variable then inner_func was executed and what was written inside inner_func gets as the output.

Example:2
Input
def outer_func(massage):
  def inner_func():
    print(f" This is the--> {massage}")
  return def inner_func
var=outer_func("I love python")
var()
Output
This is the massage-->I love python.
Example:3
Input
def outer_func(x):
  def inner_func(y):
    v=x**y
    print(v)
  return def inner_func
var=outer_func(3)
var(2)
print(var)
Output
8
Example:4
Input
def outer_func(x):
  def inner_func(y):
    return x**y
  return def inner_func
var=outer_func(2)
print(var(2))
Output
4

Recursion

Recursion means a function that can call itself. This means that we can loop through data to reach a result.

Example:1
Input
def recursion(a):
   if(a > 0):
      result = a + recursion(a - 1)
      print(result)
   else:
     result = 0
   return result
recursion(6)
Output
1
3
6
10
15
21

In the example, we used the variable as the data, which decrements -1 every time it recurs. The recursion will end when the condition is not greater than 0.

How to take input from user in a function?

Example:
Input
def input_take(a,b):
  v=(a+b)/2
  print(v)
x=int(input("Enter your first number:"))
y=int(input("Enter your second number:"))
input_take(x,y)
Output
Enter your first number:4
Enter your second number:4
4.0

CodersAim is created for learning and training a self learner to become a professional from beginner. While using CodersAim, you agree to have read and accepted our terms of use, privacy policy, Contact Us

© Copyright All rights reserved www.CodersAim.com. Developed by CodersAim.