Skip to content

Instantly share code, notes, and snippets.

@lfalanga
Last active February 16, 2020 06:23
Show Gist options
  • Save lfalanga/bcdc8e2d8f1e692e1b088c2a39ada909 to your computer and use it in GitHub Desktop.
Save lfalanga/bcdc8e2d8f1e692e1b088c2a39ada909 to your computer and use it in GitHub Desktop.
# Example 1
def tax(bill):
"""Adds 8% tax to a restaurant bill."""
bill *= 1.08
print "With tax: %f" % bill
return bill
def tip(bill):
"""Adds 15% tip to a restaurant bill."""
bill *= 1.15
print "With tip: %f" % bill
return bill
meal_cost = 100
meal_with_tax = tax(meal_cost)
meal_with_tip = tip(meal_with_tax)
# Example 2
def square(n):
"""Returns the square of a number."""
squared = n ** 2
print "%d squared is %d." % (n, squared)
return squared
# Calling the square function to be implemented
square(10)
# Example 3
def power(base, exponent): # Add your parameters here!
result = base ** exponent
print "%d to the power of %d is %d." % (base, exponent, result)
power(37, 4) # Add your arguments here!
# Example 4: Functions calling functions
def one_good_turn(n):
return n + 1
def deserves_another(n):
return one_good_turn(n) + 2
# Example 5: Passing a list as an argument
def list_function(x):
return x
n = [3, 5, 7]
print list_function(n)
# Example 6: Passing a list as an argument
def list_function(x):
return x[1]
n = [3, 5, 7]
print list_function(n)
# Example 7: Passing a list as an argument and modifying its content
def list_function(x):
x[1] += 3
return x
n = [3, 5, 7]
print n
print list_function(n)
print n
# Example 8: Passing many arguments to a function
def biggest_number(*args):
print max(args)
return max(args)
def smallest_number(*args):
print min(args)
return min(args)
def distance_from_zero(arg):
print abs(arg)
return abs(arg)
biggest_number(-10, -5, 5, 10)
smallest_number(-10, -5, 5, 10)
distance_from_zero(-10)
# Example 9: Optional arguments
def myfunc(a,b, *args, **kwargs):
for ar in args:
print ar
myfunc(a,b,c,d,e,f)
def myfunc(a,b, *args, **kwargs):
c = kwargs.get('c', None)
d = kwargs.get('d', None)
#etc
myfunc(a,b, c='nick', d='dog', ...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment