def functionName( PARAMETER1, PARAMETER2, ... ):
# STATEMENTS
return VALUE
VARIABLE = functionName( ARGUMENT1, ARGUMENT2, ...)
dividing a program into functions or sub-programs have several advantages:
# Function definition
def greet():
print('Hello World!')
# Function call
greet()
Hello World!
# void function; returns None by default
a = greet() # returned value
print('a =', a)
Hello World! a = None
type(greet)
function
# function can be assigned to a variable
myfunc = greet
type(myfunc)
function
myfunc()
Hello World!
def greet(name):
print('Hello {0}'.format(name))
greet('John Smith')
Hello John Smith
greet() # How to fix? provide either default value or call it properly
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-29-04220913ffae> in <module>() ----> 1 greet() # How to fix? provide either default value or call it properly TypeError: greet() missing 1 required positional argument: 'name'
def greet(name="Anonymous"):
print('Hello {0}'.format(name))
greet()
Hello Anonymous
user = input('Enter your name: ')
greet(user)
Enter your name: Hello
print(name)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-33-9ba126b17b03> in <module>() ----> 1 print(name) NameError: name 'name' is not defined
# global and local scope demos with various ways to pass arguments
var1 = "Alice" #global
def myFunc(a, b, c, *args, **kwargs):
global var1
var1 = "Bob" # global or local? How can we access global var1?
var2 = "John"
print('var1 = ', var1)
print('var2 = ', var2)
print('a = ', a)
print('b = ', b)
print('c = ', c)
print('*args = ', args)
print('type of args = ', type(args))
print('**kwargs = ', kwargs)
print('type of kwargs = ', type(kwargs))
myFunc(1, 'Apple', 4.5, 5, [2.5, 'b'], fname='Jake', num=1)
print(var1)
var1 = Bob var2 = John a = 1 b = Apple c = 4.5 *args = (5, [2.5, 'b']) type of args = <class 'tuple'> **kwargs = {'fname': 'Jake', 'num': 1} type of kwargs = <class 'dict'> Bob
Problem:
def add(num1, num2):
"""
takes two numeric arguments: num1 and num2
calculates and returns the sume of num1 and num2
"""
total = num1 + num2
return total
# call add to run and test
add(100, 200)
300
add(100.99, -10)
90.99
help(add)
Help on function add in module __main__: add(num1, num2) takes take numeric arguments, num1 and num2 returns the sum of num1 and num2
# complete the following function
def multiply(x, y):
"""
Function takes two numbers, x and y.
Returns the product of x and y.
FIXME
"""
pass
# help can be run for user-defined functions as well
help(multiply)
Help on function multiply in module __main__: multiply(x, y) Function takes two numbers, x and y. Returns the product of x and y. FIXME
# uint testing add function
assert add(2, 3) == 5
assert add(10, -5) == 5
# assert add(100, 2000.99) == ?
# unit testing multiply function
# write some sample test cases for multiply function using assert statement
def getAreaAndPerimeter(length, width):
"""
Function takes length and width of a rectangle.
Finds and returns area and perimeter of the rectangle.
"""
area = length*width
perimeter = 2*(length+width)
return area, perimeter
var1 = 'John' # global variable
def greetSomeone(arg1):
arg1 = 'Jake' # local variable
print('hello ', arg1)
greetSomeone(var1)
print('var1 = ', var1)
hello Jake var1 = John
Write a function that takes two numbers; subtracts the second from the first and returns the difference.
Write a function that converts seconds to hours, minutes and seconds. Function then returns the values in HH:MM:SS format (e.g., 01:09:10) Here are some tests that should pass: assert get_time(3666) == '01:01:06' assert get_time(36610) == '10:10:10'
Write a function called hypotenuse that returns the length of the hypotenuse of a right triangle given the lengths of the two legs as parameters: assert hypotenuse(3, 4) == 5.0 assert hypotenuse(12, 5) == 13.0 assert hypotenuse(24, 7) == 25.0 assert hypotenuse(9, 12) == 15.0
Write a function slope(x1, y1, x2, y2) that returns the slope of the line through the points (x1, y1) and (x2, y2). Be sure your implementation of slope can pass the following tests: assert slope(5, 3, 4, 2) == 1.0 assert slope(1, 2, 3, 2) == 0.0 assert slope(1, 2, 3, 3) == 0.5 assert slope(2, 4, 1, 2) == 2.0 Then use a call to slope in a new function named intercept(x1, y1, x2, y2) that returns the y-intercept of the line through the points (x1, y1) and (x2, y2) assert intercept(1, 6, 3, 12) == 3.0 assert intercept(6, 1, 1, 6) == 7.0 assert intercept(4, 6, 12, 8) == 5.0