Sea of Tranquility    About    Archive    Feed

Random Python notes

def is_divisible(x, y):
  return x % y == 0

# A more explicit version of the same function
def is_divisible(x, y):
  if x % y == 0:
    return True
  else:
    return False
def absolute(x):
  if x < 0:
    return -x
  if x > 0:
    return x 


In the example giveb below, x is the parameter, and 2 is the argument passed on to it.

def foo(x):
  return x**2

print(foo(x=6))
x = 999

if (x % 2 == 0):
  print("x is even")
elif (x % 9 == 0):
  print("x is divisible by 9")
elif (x % 3 == 0):
  print("x is divisible by 3")
def factorial(n):
  if n == 0:
    return 1
  else:
    recurse = factorial(n-1)
    result = n * recurse
    return result 
isinstance(4, int) #returns True
isinstance(4.0, int) #returns False
isinstance('4.0', float) #returns False

The infinite resursion seen in the factorial(n) function can be handled better by using the isinstance() function.

def factorial(n):
  if not isinstance(n, int):
    print("Factorial is defined only for integers")
    return None
  elif n < 0:
    print("Factorial is not defined for negative integers")
    return None
  elif n == 0:
    return 1
  else:
    recurse = factorial(n-1)
    result = n * recurse
    return result



from math import modf

d, i = modf(123.456) #modf() returns a tuple
print(d) # Decimal part
print(i) # Integer part


Reference

  1. Allen Downey. Think Python. How to Think Like a Computer Scientist. Green Tea Press, Needham, Massachusetts