Type Here to Get Search Results !

Develop user defined Python function ,Function with minimum 2 arguments and Function returning values

 Develop user defined Python function ,Function with minimum 2 arguments and Function returning values


Functions are the most important aspect of an application. A function can be defined as

the organized block of reusable code which can be called whenever required.

Develop user defined Python function ,Function with minimum 2 arguments and Function returning values

a) Creating a function: In Python, we can use def keyword to define the function.

Syntax:

def my_function():

 function-suite

 return <expression>


b) Calling a function: To call the function, use the function name followed by the

parentheses.

def hello_world():

 print("hello world")

hello_world()

Output:

hello world

c) Arguments in function: The information into the functions can be passed as the

argumenta. The arguments are specified in the parentheses. We can give any number

of arguments, but we have to separate them with a comma.

Example

#defining the function

def func (name):

 print("Hi ",name);

 #calling the function

func("ABC")

Output:

hi ABC


d) return Statement: The statement return [expression] exits a function, optionally

passing back an expression to the caller. A return statement with no arguments is the

same as return None.

Example

# Function definition is here

def sum( arg1, arg2 ):

 # Add both the parameters and return them."

 total = arg1 + arg2

 print "Inside the function: ", total

 return total;

# Now you can call sum function

total = sum(10, 20 );

print "Outside the function: ", total

Output:

Outside the function: 30


Example

1. Write a Python function that takes a number as a parameter and check the number isprime or not.

def prime(num):
    if(num==1):
        return "no prime"
    elif(num==2):
        return "This is prime number"
    else:
        for x in range(2,num):
            if(num%x==0):
                return "no prime"
        return "this is prime number"
print(prime(13))


2. Write a Python function to calculate the factorial of a number (a non-negativeinteger). The function accepts the number as an argument

def factorial(num):
    fact = 1
    for i in range(num,0,-1):
        fact = fact*i
    print("factorial is :",fact)
num = int(input("Enter the number :"))
factorial(num)


3. Write a Python function that accepts a string and calculate the number of upper caseletters and lower case letters

def upper(str):
    num1=0
    num2=0
    for x in range(len(str)):
        if str[x].islower():
            num1=num1+1
        elif str[x].isupper():
            num2 = num2+1
    print("number of lowercase character is :",num1)
    print("number of uppercase character is :",num2)
str = input("Enter the string :")
upper(str)
Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Below Post Ad