Você está na página 1de 7

Islamic University Of Gaza

Faculty of Engineering
Computer Engineering Department

Lab 6

Function

Eng. Ibraheem Lubbad

November 25, 2016


Functions allow us to group a number of statements into a block of cade to organized reusable
code that is used to perform a single, related action
Python gives you many built-in functions like len(), etc. but you can also create your own
functions. These functions are called user-defined functions.

Syntax of funcation
def function_name( parameters ):

return [expression]

Example:

Example 1
def print_st( ):

print "Hello from function"

return
No
parameters (inputs)

To use print_st, function you have to call the function as print_st ()

Example 1
print_st()
Example 2
One
def print_st( word ): parameter (input)
print word
return

To use print_st, function you have to call the function as print_st (input)

Example 2
print_st("Python")

Example 1
def print_st( word ):
print word
return

If you use function without pass parameter will get error.

Example 1
print_st()
 Default value:
A default value is value that assumes if a value is not provided in the function call for that
argument.

Example 1
def print_st( name="Ali" ):
print "Name : " , name
return

In this case we not pass value to so name parameter will use default value.

Example 1
print_st()

If we pass value to name, then print new value

Example 1
print_st("ibraheem")
 The return Statement
The statement return [expression] exits a function, use to passing back an expression to the
caller. A return statement with no parameter is the same as return None.
All the above examples are not returning any value. You can return a value from a function as
follows:

Write function to sum two number

Example 1
def sum_fun( num1,num2 ):
x=num1+num2

return x

print " result sum 5,9 = ",sum_fun(5,9)


Lab Work:

Q1) Write function to compute the length of sequence (String, list ,Tupe ) as len() function

Example 1

def my_len(seq):
count = 0;
for i in seq:
count=count +1

return count;

items=["orange","apple","banana",5,8]
x=my_len(items)

print "length items list = ", x

Q2) Write function to sum numbers between x to y

Example 1
def sum_range(x,y):
s=0

for i in range(x, y+1 ):


s= s+ i

return s
We can use sum_range f unction to sum numbers between 0 -10 , 1-100 and 10-50.

Example 1
def sum_range(x,y):
s=0

for i in range(x, y+1 ):


s= s+ i

return s

a= sum_range(0,10)
b= sum_range(1,100)
c= sum_range(10,50)

print "sum numbers between 0 - 10 = ", a


print "sum numbers between 1 - 100 = ", b
print "sum numbers between 10 - 50 = ", c

END

Você também pode gostar