Friday 4 December 2015

Python: functions

A function is a block of statements identified by a name. The keyword 'def' is used to define a function. Functions are mainly used for two reasons.
a.   To make code easier to build and understand
b.   To reuse the code

Syntax
def functionName(argument1, argument2 …. argumentN):

test.py
def factorial(n):
 if(n<=1):
  return 1
  
 result=1
 
 for i in range(2, n+1):
  result *= i
 return result
 
print(factorial(1))
print(factorial(2))
print(factorial(3))
print(factorial(4))
print(factorial(5))


$ python3 test.py
1
2
6
24
120

Variables created before function definition may be read inside of the function only if the function does not change the value.
test.py
# Create the x variable and set to 44
x = 44
 
# Define a simple function that prints x
def f():
 x += 1
 print(x)
 
# Call the function
f()


Run above program, you will get following error.
$ python3 test.py
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    f()
  File "test.py", line 7, in f
    x += 1
UnboundLocalError: local variable 'x' referenced before assignment

Remove ‘x+=1’ statement and re run the above program, value of x is printed to console.



Previous                                                 Next                                                 Home

No comments:

Post a Comment