***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Saturday, July 24, 2021

Value Returning Functions

A value-returning function is a function that
returns a value back to the part of the program that called it.



A
value-returning function is a special type of function.



• It is a group of statements that
perform a specific task.



• When you want to execute the function,
you call it.



When
a value-returning function finishes, it returns a value back to the part of the
program that called it.



Syntax:



def
fun():



    statements



    .



    .



    return [expression]



Example:



#
Python program to demonstrate return statement



def
add(a, b):



            # returning sum of a and b



            return a + b



def
is_true(a):



            # returning boolean of a



            return bool(a)



#
calling function



res
= add(2, 3)



print("Result
of add function is {}".format(res))



res
= is_true(2<5)



print("\nResult
of is_true function is {}".format(res))


Standard Library functions

Python,
as well as most other programming languages, comes with a
standard library of
functions that have already been written( known as
library functions ). Many of the functions in the standard
library, however, are stored in files that are known as modules. These
modules, which are copied to your computer when you install Python, help
organize the standard library functions.



In
order to call a function that is stored in a module, you have to write an
import statement at the top of your program. An import statement tells the
interpreter the name of the module that contains the function.



Ex:



import
math



The
math module contains various mathematical functions that work with
floatingpoint numbers.

Ø  The
math Module

The
math module in the Python standard library contains several functions that are
useful for performing mathematical operations. These functions typically accept
one or more values as arguments, perform a mathematical operation using the
arguments, and return the result.


The
math module also defines two variables, pi and e, which are assigned
mathematical values for pi and e. These variables can be used in
equations that require their values.



Example:



area
= math.pi * radius**2


Global Variables and Global Constants

When
a variable is created by an assignment statement that is written outside all
the functions in a program file, the variable is
global. A global variable
can be accessed by any statement in the program file, including the statements
in any function.



Example:



#Create
a global variable.



 number = 0



def
main():



show_number()



def
show_number():



print('The number you entered is',
number)



#
Call the main function.



main()

An
additional step is required if you want a statement in a function to assign a
value to a global variable.



Example:

Most
programmers agree to restrict the use of global variables, or not use them at
all. The reasons are as follows:


Global variables make debugging difficult. Any statement in a program file can
change the value of a global variable. In a program with thousands of lines of
code, it can be difficult to track down the statement which is changing to
wrong value in global variable.


Functions that use global variables are usually dependent on those variables. To
use such a function in a different program, most likely you will have to
redesign it so it does not rely on the global variable.








Global variables make a program hard to understand. A global variable can be
modified by any statement in the program. If you are to understand any part of
the program that uses a global variable, you have to be aware of all the other
parts of the program that access the global variable.


Ø  Global
Constants

A
global constant is a global name that references a value that cannot be
changed. Because a global constant’s value cannot be changed during the
program’s execution, the potential hazards that are associated with the use of
global variables are avoided.





Although
the Python language does not allow you to create true global constants, you can
simulate them with global variables. If you do not declare a global variable
with the global key word inside a function, then you cannot change the
variable’s assignment inside that function.



Passing Arguments to Functions

An argument is any piece of data that is passed into
a function when the function is called. A parameter is a variable that receives
an argument that is passed into a function.



If
a function needs to receive arguments when it is called, the function must have
with one or more parameter variables. A parameter variable, often simply
called a parameter, is a special variable that is assigned the value of
an argument when a function is called. A function may not take any parameters, may
take one parameter or take multiple parameters.



Example:



In
addition to this conventional form of argument passing, the Python language
allows you to write an argument in the following format, to specify which
parameter variable the argument should be passed to:



parameter_name=value



In
this format, parameter_name is the name of a parameter variable and
value is the value being passed to that parameter. An argument that is written
in like this syntax is known as a keyword  argument.



Example:



It
is possible to mix positional arguments and keyword arguments in a function
call, but the positional arguments must appear first, followed by the keyword
arguments. Otherwise an error will occur.



show_interest(10000.0,
rate=0.01, periods=10)



In
this statement, the first argument, 10000.0, is passed by its position to the
principal parameter. The second and third arguments are passed as keyword
arguments.



#
This will cause an ERROR!



show_interest(1000.0,
rate=0.01, 10)



because
a non-keyword argument follows a keyword argument.


Local Variables

A
local variable belongs to the function in which it is created, and only
statements inside that function can access the variable. An error will occur if
a statement in one function tries to access a local variable that belongs to
another function.


A
variable’s scope is the part of a program in which the variable may be
accessed. A variable is visible only to statements in the variable’s scope. A
local variable’s scope is the function in which the variable is created. A
local variable cannot be accessed by code that appears inside the function at a
point before the variable has been created. Because a function’s local
variables are hidden from other functions, the other functions may have their
own local variables with the same name.



Hierarchy Charts

Flowcharts
are good tools for graphically depicting the flow of logic inside a function,
but they do not give a visual representation of the relationships between
functions. A hierarchy chart, which is also known as a structure chart, shows
boxes that represent each function in a program. The boxes are connected in a
way that illustrates the functions called by each function.



Tuesday, June 15, 2021

Introduction to Functions

A function is a group of statements within a program
that exists for the purpose of performing a specific task.



A
program that has been written with each task in its own function is called a modularized
program.


1. Benefits
of Modularizing a Program with Functions



Simpler
Code:
A program’s code tends to
be simpler and easier to understand when it is broken down into functions.
Several small functions are much easier to read than one long sequence of statements.



Code
Reuse:
Functions also reduce the duplication of code within
a program. If a specific operation is performed in several places in a program,
a function can be written once to perform that operation and then be executed
any time it is needed.



Better
Testing:
When each task within a program is contained in its
own function, testing and debugging becomes simpler. Programmers can test each
function in a program individually, to determine whether it correctly performs
its operation. This makes it easier to isolate and fix errors.



Easier
Facilitation of Teamwork:
Functions also make it easier for
programmers to work in teams. When a program is developed as a set of functions
that each performs an individual task, then different programmers can be assigned
the job of writing different functions. It leads to faster development.

2. Void
Functions and Value-Returning Functions

There are two types of functions: void functions and
value returning functions.

When a void function is called, it simply executes the statements it contains and
then terminates. When a value-returning function is called, it executes the statements that it contains, and then
it returns a value back to the statement that called it.

3. Defining
and Calling a Function

To create a function you write its definition.
Here is the general format of a function definition in Python:

def function_name():

statement

statement

etc.

The first line is known as the function header.
It marks the beginning of the function definition.

The function header begins with the key word def,
followed by the name of the function, followed by a set of parentheses,
followed by a colon.

The next line is a set of statements known as a
block. A block is simply a set of statements that belong together as a
group.

A function definition specifies what a function
does, but it does not cause the function to execute. To execute a function, you
must call it.

When a function is called, the interpreter jumps to
that function and executes the statements in its block. Then, when the end of
the block is reached, the interpreter jumps back to the part of the program
that called the function, and the program resumes execution at that point.

Example:

# This program demonstrates a function.

# First, we define a function named message.

def message():

print('I am
Ashraf,')

print('computer
science faculty.')

 # Call the
message function.

message()

In fact, it is common for a program to have a main
function that is called when the program starts. The main function then calls
other functions in the program as they are needed. It is often said that the
main function contains a program’s mainline logic, which is the overall logic
of the program.

Example:

# This program has two functions.

# define the main function.

def main():

print('I have
a message for you.')

message()

print('Goodbye!')

# Next we define the message function.

def message():

print('I am
Ashraf,')

print('computer
science faculty.')

# Call the main function.









































































main()

Designing
a Program to Use Functions



Programmers commonly use a technique known as
top-down design to break down an algorithm into functions.



This process is called top-down design because the programmer
begins by looking at the topmost level of tasks that must be performed and then
breaks down those tasks into lower levels of subtasks.



The
process of top-down design is performed in the following manner:



·        
The overall task that the program is to
perform is broken down into a series of subtasks.



·        
Each of the subtasks is examined to
determine whether it can be further broken down into more subtasks. This step
is repeated until no more subtasks can be identified.



·        
Once all of the subtasks have been identified,
they are written in code.