Functions
Functions
- A function is a group of statements that perform a specific task.
- If a program is large, it is divided into smaller programs called sub program or modules.
- Each subprogram specified one or more actions to be performed for the larger program. Such subprograms are called as functions.
Types
- Pre-defined (or) Built-in.
- User defined.
Built-in functions:
Built-in functions are functions already built into python interpreter and are readily available for use.
Example:
- print()
- input()
Program:
A=int(input("Enter a number"))
print(A)
User defined functions:
- The functions defined by the users according to their requirements are called user-defined functions.
- The user can modify the function according to their requirements.
Defining a function:
- Functions in python are defined using the block keyword def followed by the function name and parentheses ( ). Function defined includes:
- A header, which begins with a keyword def and end with a colon.
- A body consisting of one or more python statements each indented the same amount (4spaces is tha python standard) from the header
Example:
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
A=int(input("Enter first number:"))
B=int(input("Enter second number:"))
print(gcd(A,B))
Flow of execution:
- Flow of execution specifies the order in which statements are executed.
- Program execution starts from first statement of the program. One statement is executed at a time from top to bottom.
- Function definitions do not alter the flow of execution of the program and the statements inside the function are not executed until the function is called.
- When a function is called the control flow jumps to the body of the function, executes the function, and return back to the place in the program where the function call was made.

No comments:
Post a Comment