You can learn about Functions in Python Programs with Outputs helped you to understand the language better.
Python Programming – Top-Down Approach Of Problem Solving
Top-down design is the technique of breaking down a problem into various major tasks needed to be performed. Each of these tasks is further broken down into separate subtasks, and so on till each sub-task is sufficiently simple to be written as a self-contained or procedure module. The entire solution to the problem will then consist of a series of simple modules.
In top-down design, you initially describe the problem you are working on at the highest or most general level. The description of the problem at this level will usually be concerned with what must be done – not how it must be done.
- Introduction to Python Programming – The Basic Model Of Computation
- Introduction to Python Programming – Programming Languages
- Introduction to Python Programming – Documentation
The description will be in terms of complex, higher-level operations. You must take all of the operations at this level and individually break them down into simpler steps that begin to describe how to accomplish the tasks. If these simple steps can be represented as acceptable algorithmic steps, you need not split them any further. If that is not the case, then you split each of these second-level operations individually into still simpler steps. This stepwise refinement continues until each of the original top-level operations has been described in terms of acceptable shortest (primitive) statements.
- The top-down approach is used in the system analysis and design process.
The top-down approach, starting at the general levels to gain an understanding of the system and gradually moving down to levels of greater detail is done in the analysis stage. In the process of moving from top to bottom, each component is exploded into more and more details.
Thus, the problem at hand is analyzed or broken down into major components, each of which is again broken down if necessary.
- The top-down process involves working from the most general down to the most specific.
The design of modules is reflected in hierarchy charts such as the one shown in Figure 10.1. The purpose of procedure Main is to coordinate the three branch operations e.g. Get, Process, and Put routines. These three routines communicate only through Main. Similarly, Sub1 and Sub2 can communicate only through the Process routine.
- Using the top-down approach, attention is first focussed on global aspects of the overall system. As the design progress takes place, the system is decomposed into subsystems and more consideration is given to specific issues.
Advantages of Top-down Approach
The advantages of the top-down approach are as follows:
a. This approach allows a programmer to remain “on top of” a problem and view the developing solution in context. The solution always proceeds from the highest level downwards. With other techniques, you may find yourselves bogged down with very low-level decisions at a very early stage. It will be difficult to make these deci¬sions if it is not clear as to how they may affect the overall solution of the problem.
b. This would be a very good way to delay deci¬sions on problems whose solution may not be readily available. At each stage in the development, the individual operation will be split up into a number of more elementary steps. If you are not sure how to proceed with Step 1 you can still work on Step 2.
c. By dividing the problem into a number of sub-problems, it is easier to share problem development. For example, one person may solve one part of the problem and the other person may solve another part of the problem.
d. Since debugging time grows quickly when the program is longer, it will be to our advantage to debug a long program divided into a number of smaller segments or parts rather than one big chunk. The top-down development process specifies a solution in terms of a group of smaller, individual subtasks. These subtasks thus become the ideal units of the program for testing and debugging.
If you add a new piece of code, say “p” to the overall program “P”, and an error condition occurs, you can definitely state that the error must either be in “p” itself or in the interface between “p” or “P” because “P” has been previously checked and certified.
By testing the program in small pieces, you greatly simplify the debugging process. In addition, you will have the satisfaction of knowing that everything you have coded so far is correct.
e. Another advantage of the top-down development process is that it becomes an ideal structure for managing and implementing a program using a team of programmers. A senior programmer can be made responsible for the design of a high-level task and its decomposition into subtasks. Each of those subtasks can then be “given out” to a junior programmer who works under the direction of the senior staff. Since almost all software projects are done by teams of two or more programmers, this top-down characteristic helps in faster completion of the system.
In summary, the top-down method is a program design technique that analyses a problem in terms of more elementary subtasks. Through the technique of stepwise splitting, you expand and define each of the separate subtasks until the problem is solved. Each subtask is tested and verified before it is expanded further. Thus, there are additional advantages:
a. Increased comprehension of the problem.
b. Unnecessary lower-level detail is removed.
c. Reduced debugging time.
Bottom-up Approach of Problem Solving
When faced with a large and complex problem, it may be difficult to see how the whole thing can be done. It may be easier to solve parts of the problem individually, taking the easier aspects first and thereby gaining the insight and experience to tackle the more difficult tasks, and finally to try and join them all together to form the complete solution. This is called a bottom-up approach.
This approach suffers from the disadvantage that the parts of the program may not fit together easily. There may be a lack of consistency between mod¬ules, and considerable re-programming may have to be carried out. Hence, this approach is not much favored.
Docstrings
Docstrings serve as documentation for your function to describe what the function does in the pro¬gram so that anyone who reads the function’s docstring understands what your function does, without having to go through all the code in the function definition. These are optional constructs enclosed by triple quotes. It is a comment in the programming language.
Function Parameters and Arguments
Parameters are the value(s) provided in the parenthesis when you write the function header. You can add as many parameters as you want, just separate them with a comma.
- In other words, the parameter is a name used inside a function to refer to the value passed as an argument.
Arguments are the value(s) provided in function call/invoke statement. This value is assigned to the corresponding parameter in the function. The vari¬ables you write after your function name in def statements are often called the formal parameters of the function. The values you supply when you call the function are called the actual parameters, or argu¬ments. By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.
It is common to say that the function takes arguments and returns the result. The return statement can contain an expression that gets evaluated and the value is returned. If there is no expression in the statement or the return statement itself is not present inside a function, then the function will return the None object.
- The parameter passed by the client is known as the actual parameter. The parameter specified by the function is called the formal parameter.
- The argument is a value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.
Parameters are placeholders for information that you give to a function so it can carry out an action. For example, if a function is defined as follows:
def display(message):
then, the message is a parameter or formal argument. Although display has only one parameter, the function can have many. To define functions with multiple parameters, list them out, separated by commas.
In the following statement, It will display a message for you is an argument or actual argument, display(“It will display message for you”)
Here are a few things to know about function parameters:
(a) A function can have any number of parameters (or no parameters).
(b) When you define a function, you specify how many parameters it has.
(c) You can define default values for any or all of the parameters.
Here are a few things to know about arguments:
(a) Arguments are passed when you call the function.
(b) If the parameter has a default value, you don’t have to pass an argument.
(c) You can pass an argument as a literal or as a name.
- The values being passed through a function-call statement are called arguments or actual arguments. The values received in the function definition or header are called parameters or formal parameters.
In Example 4 shown above i.e. def power(x, n): x and n are known as parameters or formal parame¬ters.
Whereas in PW = power(a, b)
a and b are known as arguments or actual arguments.
Arguments in Python can be literals, variables, or expressions.
- Function header cannot contain expressions.
Anonymous functions
You can use the lambda keyword to create small anonymous functions. These functions are called anonymous because they are not declared in the standard manner by using the def keyword.
(a) Lambda forms can take any number of argu¬ments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
(b) An anonymous function cannot be a direct call to print because lambda requires an expression.
(c) Lambda functions have their own local name¬space and cannot access variables other than those in their parameter list and those in the global namespace.
(d) Although it appears that lambdas are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is bypassing function stack allocation during invocation for performance reasons.
Syntax:
The syntax of lambda functions contains only a single statement, which is as follows:
lambda [argl [,arg2, argn]]:expression
Following is the example to show how lambda form of function works:
Example
Demo of Anonymous function.
# Function definition sum = lambda arg1, arg2: arg1 + arg2; # call sum as a function print(“Value of total : ” , sum ( 10 , 20 ) print(“Value of total : ” , sum ( 20 , 20 )RUN >>> Value of total: 30 Value of total: 40 >>> |
The return STATEMENT
A Python function could also optionally return a value. This value could be a result produced from your function’s execution or even be an expression or value that you specify after the keyword ‘return’. And, after a return statement is executed, the program flow goes back to the state next to your function call and gets executed from there. So, to call a Python function at any place in your code, you will only have to use its name and pass arguments in its parentheses, if any. A return statement with no arguments is the same as a return None.
Example
Demo of return statement.
# Function definition 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 )def add_num(x,y): sum = x + y return sum num1 = 2 num2 = 5 print(“The sum is”. add_num(num1, num2))RUN >>> Inside the function: 30 Outside the function: 30 The sum is 7 >>> |
Let’s Try
def add_num(x,y): sum = x + y return sum num1 = 2 num2 = 5 print(“The sum is”, add_num(num1 , num2)) |
Lifetime and Scope of Variables
A variable’s lifetime is the period of time for which it resides in the memory. The lifetime of variables inside a function is as long as the function executes. They are destroyed once you return from the function. Hence, a function does not remember the value of a variable from its previous calls.
All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. The variable declared in one part of the program may not be accessible to the other parts. The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python.
- Global scope
- Local scope
Variables that are defined inside a function body have a local scope. In other words, it is local to that function and those defined outside have a global scope. This means that local variables can be accessed only inside the function in which they are declared, If you then try to access the variable x outside the function, it will give NameError.
Global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope,
def func1 ( ) :
x=9 # Local scope
print(x)
func1 ( )
>>>
9
>>>
y=9 # Global scope
def func2():
print(y)
func2 ( )
>>>
9
>>>
Let us discuss the global scope of a variable in brief.
(a) The global names are variables assigned at the top level of the enclosing module file. It means that it is visible everywhere within the program.
(b) The global names must be declared only if they are assigned within a function.
(c) Global variables must be referenced within a function without being declared. See Example
14.
Example
Demo of local and global variables.
total = 0; # This is global variable. # Function definition def sum( arg1, arg2 ): # Add both the parameters and return them. total = arg1 + arg2; # Here total Is local variable . print(“Inside the function local total : “, total) return total # Now you can call sum function sum( 20, 40 ) print(“Outside the function global total : “, total) |
When the above code is executed, it produces following result:
Inside the function local total: 60
Outside the function global total: 0
global Statements
The global statements are remotely like declaration statements in Python. They do not type or size declarations, though they are namespace declarations. The global statement tells Python that a function plans to change one or more global names, i.e., names that live in the enclosing module’s scope (namespace).
A namespace is a practical approach to define the scope, and it helps to avoid name conflicts.
void FUNCTION
A function that doesn’t return a value is called a void function or non-fruitful function whereas a function that returns a value is called fruitful function, void functions might display something on the screen or have some other effect, but they don’t have a return value. If you try to assign the result to a variable, you get a special value called None.
A void function internally returns an empty value None.
Library functions
Input ( )
Input ( ) is built-in functions, used to obtain informa-tion from the user.
>>> input ( ” Enter a number : ” )
Enter a number: 57
‘ 57 ‘
Note that this returns the input as a string. If you want to take 57 as an integer, you need to apply the int() function to it. The int( ) converts a value to an integer.
>>> int(input(“Enter a number”))
Enter a number: 57
57
Example
Demo of Input ( ) function.
#Demo of Input 0 function print ( ‘ Please enter some text : ‘ ) x = input ( ) print ( ‘ Text entered is : ‘ , x ) print ( ‘ Type : ‘ , type ( x ) ) print ( ‘ Please enter an integer value : ‘ ) x = input ( ) print ( ‘ Please enter another integer value : ‘ ) y = input ( ) num1 = int(x) num2 = int(y) print(num1, ‘+’, num2, ‘=’, num1 + num2)RUN >>> Please enter some text: Hello Text entered is: Hello Type: <class ‘str’> Please enter an integer value: 4 Please enter another integer value: 2 4 + 2 = 6 >>> |
eval ( )
The eval ( ) function converts a string containing a valid expression to an object. For example,
x = 9
print(eval(‘x + 1’))
>>>
10
>>>
>>> c = eval ( ” 3 , 5 , 6 ” ) # c = ( 3 , 5 , 6 )
>>> c
( 3 , 5 , 6 )
>>>
print ( )
The print ( ) function enables a Python program to display textual information to the user,
print(“Hello, World!”)
print(“I am learning Python”)