In: Computer Science
Task 2: Debugging and writing functions
def mysum(x, y)
""" takes two numbers and returns their sum """
total = x + y
print(total)
>>> mysum(44, 67)
>>> print(mysum(10, 7))
What happens? Why?
(Use the MS Word file “Task2 steps”, and write your answer to this step.)
>>> sum_double(1, 2)
3
>>> sum_double(3, 2)
5
>>> sum_double(2, 2)
8
Be sure to write a docstring for the function.
After writing the function, test it in two ways:
def test():
""" function for testing """
test1 = sum_double(1, 2)
print('first test returns', test1)
# Add more tests below
This code provides the beginnings of a test function, with lines that call the function with a set of inputs and print the return value. It’s worth noting that this function does not need a return statement, because its sole purpose is to make test calls and print their results.
You should:
(Use the MS Word file “Task2 steps”and write what you did in this step.)
Task2 Steps:
1. Syntax Error: Invalid Syntax
This error can be fixed adding colon at the end of the first line of function defination.
2. IndentationError: expected an indented block
This error can be fixed by giving the tab space before the doc string.
3. Test case 1: mysum(44, 67)
This test case will work correctly and will give the expected output.
4. Test case 2: print(mysum(10, 7))
This test case is returning None along with printing the output. This can be fixed by changing the last line of the function defination from "print(total)" to "return total".
Modified Code
def mysum(x, y):
""" takes two numbers and returns their sum """
total = x + y
return total
hw4Task2.py
sumdouble function
def sum_double(a, b):
"""returns the sum if two integers are not same, otherwise returns double of sum"""
#return double of sum if two numbers are same
if(a == b):
return 2*(a+b)
#return sum if two numbers are not same
else:
return (a+b)
test function
def test():
"""function for testing"""
#first test case
test1 = sum_double(1,2)
#second test case
test2 = sum_double(3,2)
#third test case
test3 = sum_double(2,2)
#print the results
print('first test returns', test1)
print('second test returns', test2)
print('third test returns', test3)
function call
test()
Steps:
1. create the function sum_double which takes two parameters as input.
2. check the condition if both the numbers are equal.
3. return double of sum if both the numbers are equal otherwise return sum.
4. create the function test which tests the sum_double function.
5. write 3 function calls to check the input test cases.
6. print the result of the test cases.
7. call the function test to get the result.
All the function has been given with the heading, also comments has been provided for the reference.
Please execute the code in IDE to get the output.