Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Python Programming: Four questions: Question 1: Write a function add that can ta

ID: 671595 • Letter: P

Question

Python Programming:

Four questions:

Question 1: Write a function add that can take any number of arguments and returns their sum. Test in main with the following calls.

    add(1)

    add(1,2,3)

    add()

     add(1,2,3,4,5)

Execution Listing:

>>>

1

6

0

15

Question 2: Complete the following function add(). Note that the function add() needs to sum and return all arguments passed to it. You can add to add() but don’t make any other modifications. Hint: you will need to use None.

def main():

    print( add(1,2,3,4) )

    print( add(1,2,3) )

    print( add(1,2) )

    print( add(1) )

    print( add() )

def add( first , second , third = 1, fourth = 1 ):

if __name__ == "__main__": main()

Execution Listing:

>>>

10

7

5

3

2

Question 3: Write a function highScore that can take a variable number of named arguments and display the one with the highest score (or value).

def main():

    highScore( ann = 100, bob = 90, carol = 80, dave = 70)

    highScore( ann = 100, bob = 90, carol = 80, dave = 70, ed = 69)

    highScore( ann = 100, bob = 90)

Execution Listing:

>>>

The highest score was: ann 100

The highest score was: ann 100

The highest score was: ann 100

Question 4: Write a generator function called monthDays that will generate the days in the months. It takes two arguments (start, months). The first indicates which month to start with. The second indicates the number of months.

For example:

monthDays(3,3) will yield 30, 31 and 30 because those are the number of days in April, May and June.

Both arguments should have default values. The default value for start should be 0 and the default value for months should be 12. In other words, if the default values are used, all we months of the year should be displayed.

Test with:

monthDays(3,3)

and

monthDays()

Execution Listing:

>>>

30

31

30

>>>

31

28

31

30

31

30

31

31

30

31

30

31

Explanation / Answer

3)
import pickle
# load the previous score if it exists
try:
with open('score.dat', 'rb') as file:
score = pickle.load(file)
except:
score = 0
print "High score: %d" % score
# your game code goes here
# let's say the user scores a new high-score of 10
score = 10;
# save the score
with open('score.dat', 'wb') as file:
pickle.dump(score, file)
***
import shelve
d = shelve.open('score.txt')
d['score'] = score         
d.close()

1)
def mySum(*args):
if len(args) == 1:
return args[0]
else:
return args[-1] + mySum(*args[:-1])