Python Function
Python Function- Write Once, Use Many Times
Introduction
Imagine you need to calculate the sum of two numbers many times in your programs with different values.
Will you write the code again and again?
No.
Instead, you create a function in a program, that
- can have arguments, if needed
- can perform certain functionality
- can return a result
What is a Function?
A function is a block of code that performs a specific task. In Python we create functions using the def keyword.
Basic Function Syntax
def function_name():
#code
Example:
def calcSomething (x):
r=2* x**2
return r
a= int(input("Enter a number:"))
print(calcSomething(a))
1. Where x is the argument to function calcSomething
2. return statement returns the computed result.
3. calcSomething(a) calls the function.
Calling/Invoking/Using a Function
To use a function that has been defined earlier, you need to write a function call statement in Python. A function call statement takes the following form:
<function-name>(<value-to-be-passed-to-argument>)
For example, if we want to call the function calcSomething() defined above, our function call statement will be like :
calcSomething(a) #value 5 is being sent as a argument
Function with Return Value
Function can also return results.
Code:
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Output:
8
return sends the result back.
Real-Life Example: Even or Odd
def check_even(num):
if num % 2 ==0:
return "Even"
else:
return "Odd"
print(check_even(10))
Why Use Functions?
- It gives program a clean structure.
- It is easy to debuge
- Reusable logic
- Professional coding style
Practice Questions (Very Important)
- Create a function to find square of a number
- Create a function to find factorial
- Create a function to check if number is positive or negative
- Create a function to calculate simple interest
- Create a function to find largest of three numbers
Comments
Post a Comment