Functions in Python Programming
Functions in Python Programming
x = math.cos(radians)
golden = (math.sqrt(5) + 1) / 2
When you call a function in interactive mode, Python displays the result:
>>> math.sqrt(5)
2.2360679774997898
But in a script, if you call a fruitful function all by itself, the return value
is lost forever!
math.sqrt(5)
e = math.exp(1.0)
height = radius * math.sin(radians)
def area(radius):
a = math.pi * radius**2
return a
def area(radius):
return math.pi * radius**2
def absolute_value(x):
if x < 0:
return -x
else:
return x
>>> absolute_value(0)
None
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result
radius = distance(xc, yc, xp, yp)
result = area(radius)
>>> is_divisible(6, 4)
False
>>> is_divisible(6, 3)
True
def is_divisible(x, y):
return x % y == 0
if is_divisible(x, y):
print('x is divisible by y')
if is_divisible(x, y) == True:
print('x is divisible by y'
Factorial using recursion
def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result
def fibonacci (n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
Checking input
def factorial (n):
if not isinstance(n, int):
print('Factorial is only defined for integers.')
return None
elif n < 0:
print('Factorial is not defined for negative integers.')
return None
elif n == 0:
return 1
else:
return n * factorial(n-1)
>>> factorial('fred')
Factorial is only defined for integers.
None
>>> factorial(-2)
Factorial is not defined for negative integers.
None