FUNCTIONS
What is a function in python.
To complete a repeated task and writing the same code again and again ,we use function to call the same code just by calling it .
Function starts with def keyword followed by function name and parameter in parenthesis.
def ()
Creating a function.
We can create a function by using def keyword.
def new_func():
print("This is new fucntion")
Calling of function
After creating a function we can use it by calling.
def new_func():
print("calling of function.")
new_func()
output:-calling of function.
Calling a function with parameters
.
def multiply(x,y):
z=x*y
return z
print(multiply(2,4))
print(multiply(4,5))
output:-8
20
Arguments in functions.
Arguments are the values passed inside a parameter.
def odd_even(x):
if x%2==0:
print("even")
else:
print("odd")
odd_even(9)
odd_even(10)
output:- odd
even
Return function .
Return function is used to exit from function and return value assigned to it. A return can consists of expression ,string ,constant etc.
def ret():
return "return works like this ;)"
print(ret())
output:- return works like this;)*
Nested function
We can use a function inside a function and can make code more advanced.
def sum():
x=4+5
def multiply():#nested function defined as multiply
z=x*5#multiplying x with 5
print(z)
multiply()#calling nested func inside main func.
sum()#calling main function.
output:- 45
Some examples :
1. Ask 5 numbers from user and return odd or even
def odd(x):
if x%2==0:
return "even"
else:
return "false"
i=1
while i<=5:#for five number of attempts
y=int(input("enter x "))
print(odd(y))
i+=1
output:-enter x 12
even
enter x 23
false
enter x 34
even
enter x 45
false
enter x 56
even
2. To find maximum of two numbers.
def max(x,y):
if x>y:
print(x,"is greater than ",y)
else:
print(y,"is greater than ",x)
x=int(input("Enter first number :-"))
y=int(input("Enter second number:-"))
max(x,y)
output:Enter first number :-12
Enter second number:-322
322 is greater than 12
3. Sum of all numbers in a list.
list=[]
i=1
while i<=5:
x=int(input("Enter elements of list:-"))
list.append(x)
i+=1
print("List you have entered :",list)
def sum():
add=0
for j in range(5):
add+=list[j]
print("Sum of all the elements of list is ",add)
sum()
output:Enter elements of list:-12
Enter elements of list:-12
Enter elements of list:-12
Enter elements of list:-12
Enter elements of list:-12
List you have entered : [12, 12, 12, 12, 12]
Sum of all the elements of list is 60