Working With Functions
Working With Functions
A function is a group of statements that exits within a program for the purpose of
performing a specific task.
Functions types:
Functions can be categorized into three types:
i. Built-in function
ii. Functions defined in modules
iii. User defined functions
Built-in Functions: Built-in functions are the pre-defined functions that are always available
in the standard library to make programing easier, faster and more powerful.
Output:
2
Output:
25
random module (Generating Random Numbers)
import random
randrange(): This function generate an integer between its lower and upper argument.
print(random.randrange(10))
print(random.randrange(5,10))
print(random.randrange(1,8,2))
print(random.randrange(2,8,2))
Arun
name=["Amit","Arun","Ajay","Anjali"]
lt=len(name) Output2:
n=random.randrange(0,lt) Ajay
print(name[n])
random(): This function generates a random number from 0 to 1 such as
0.9715177405160377. It takes no parameters and returns values between 0 and 1(including 0,
but excluding 1).
print(random.random()) n=random.random())
Output: print(round(n,5))
i. 0.7606971546672353 Output:
ii. 0.6686850133435913
i. 0.42998
ii. 0.40281
randint(): this function accept two parameters, a and b as the lowest and highest number,
returns a number randomly in the inclusive range [a,b].
print(random.randint(1,10)) print(randint(1,10))
Output: Output:
i. 3 i. 5
ii. 1 ii. 10
iii. 6 iii. 9
uniform(): this fuction returns a random floating-point number in between two numbers.
Syntax: random.uniform(x, y)
The returns random floating point number is greater than or equal to x and less than y.
Syntax: random.choice(sequence)
import random
name=["Amit","Arun","Ajay","Anjali"]
ch_name=random.choice(name)
print(ch_name)
Output 1: Arun
Output 2: Anjali
User defined functions: These are defined by the programmer as per requirement.
Define and call a faction in python:
Syntax:
<statements>
Example:
Keyword def Function Name
name
def opsmsg( ):
def opsmsg( ): Fuction Hearder
Function
Definition
print(" wel come to oxford public school")
print(" Welcome to Oxford Public School") Function Body
c=a+b
sum( )
Function Call
sum( )
Output 1: Output 2:
def sum( ):
def sum( ):
st
a=int(input("Enter 1 no:"))
a=int(input("Enter 1st no:"))
b=int(input("Enter 2nd no:"))
b=int(input("Enter 2nd no:"))
c=a+b
c=a+b
return
return c
s=sum()
s=sum()
print("sum of two numbers: ",s)
print("sum of two numbers: ",s)
Output: sum of two numbers: None
#program to calculate addition, and subtraction of two no.
def calc( ):
add=a+b
sub=a-b
#.........ma p …………
add, s=calc()
Output:
def calc( ):
add=a+b
sub=a-b
print("End")
#.........main prog…………
result=calc()
Output: