12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

oth arguments, feel free to pick a value from either. Test your function by writingit in a file and running the file as a script. What happens if you pass listsinstead of dictionaries? How could you generalize your function to handle thiscase, too? (Hint: see the type built-in function used earlier.) Does the order ofthe arguments passed in matter?7. More argument-matching examples. First, define the following six functions(either interactively or in a module file that can be imported):def f1(a, b): print a, b# Normal argsdef f2(a, *b): print a, bdef f3(a, **b): print a, bdef f4(a, *b, **c): print a, b, cdef f5(a, b=2, c=3): print a, b, c# Positional varargs# Keyword varargs# Mixed modes# Defaultsdef f6(a, b=2, *c): print a, b, c# Defaults and positional varargsNow, test the following calls interactively, and try to explain each result; in somecases, you’ll probably need to fall back on the matching algorithm shown inChapter 16. Do you think mixing matching modes is a good idea in general? Canyou think of cases where it would be useful?>>> f1(1, 2)>>> f1(b=2, a=1)>>> f2(1, 2, 3)>>> f3(1, x=2, y=3)>>> f4(1, 2, 3, x=2, y=3)>>> f5(1)>>> f5(1, 4)>>> f6(1)>>> f6(1, 3, 4)8. Primes revisited. Recall the following code snippet from Chapter 13, which simplisticallydetermines whether a positive integer is prime:x = y / 2 # For some y > 1while x > 1:if y % x == 0:# Remainderprint y, 'has factor', xbreak# Skip elsex = x-1else:# Normal exitprint y, 'is prime'380 | Chapter 17: Advanced Function Topics

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!