Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Python Function

Copyright
© © All Rights Reserved
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python Function

Copyright
© © All Rights Reserved
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
You are on page 1/ 8

PYTHON FUNCTION

A function is a set of code that performs any


given task, enabling the programmer to
modularize a program. All variables created in
function definitions are local variables; they are
known only to the function in which they are
declared.

Advantages of Functions in Python


•By including functions, we can prevent repeating the same code
block repeatedly in a program.
•Python functions, once defined, can be called many times and from
anywhere in a program.
•If our Python program is large, it can be separated into numerous
functions which is simple to track.
PYTHON FUNCTION HAS TWO PARTS:-

Function Definition and function call

Syntax of Function definition:-

def Function_name(argument list):


-------------------------------
--------------------------------Function body
return statement

# arguments and return staements are


optional
def My_function():
print(“Hello world”)

My_function() # function call

Output:
Hello world
Types of Arguments
1. Default arguments
Functions can be defined with default arguments. If the
values for the arguments are not supplied when the
function is called, the default argument is used.

def my_function(country='India'):
print("I am from:", country)

my_function("Australia")
my_function("USA")
my_function()

output
I am from: Australia
I am from: USA
I am from: India
2. Arbitrary arguments
Arbitrary arguments are used when you want the function to
take an unlimited number of arguments. When you add an
asterisk ( * ), it will receive a tuple of arguments.

def my_function(*args):
print(args)

my_function(2,6,9,3,7)

Output
(2,6,9,3,7)
3. Keyword arguments
You can pass the arguments in a non-positional
manner using keyword arguments. Let’s look at an
example to understand this:
The Return Statement in Python Functions
To return a value from a function, we use a return
statement. It “returns” the result to the caller.

def test(n1,n2):
sum=n1+n2
return sum

x=int(input("Enter the first number:"))


y=int(input("Enter the second number:"))
print("The Sum is=",test(x,y))
# check How many even and odd numbers in a range of numbers passing by list

def count(L1):

even=0
odd=0
for i in L1:

if i%2==0:
even=even+1
else:
odd=odd+1
return even, odd
n=int(input("How many numbers U want to check?"))

L1=[]
for i in range(n):
L1.append(int(input("Enter the numbers:")))
even, odd=count(L1)
print("Total even numbers =",even)
print("Total odd numbers=",odd)

You might also like