Download presentation
Presentation is loading. Please wait.
Published byEvan McDowell Modified over 6 years ago
1
Fundamentals of Programming I Default and Optional Parameters
Computer Science 111 Fundamentals of Programming I Default and Optional Parameters
2
Arguments and Return Values
A function can receive data (arguments) from its caller A function can return a single value to its caller y = math.sqrt(x)
3
Why Use Parameters? Parameters allow a function to be used with different data in different parts of a program The general method or algorithm is the same, but the arguments vary with the situation >>> math.sqrt(2) >>> math.sqrt(16) 4.0 >>>
4
Default and Optional Parameters
One or more parameters can have default values, so the caller can omit some arguments >>> round(3.1416) # Default precision is 0 3 >>> round(3.1416, 3) 3.142 >>> list(range(5)) # Default lower bound is 0, and [0,1,2,3,4] # default step value is 1 >>> list(range(1, 5)) [1,2,3,4] >>> list(range(1, 5, 2)) [1,3]
5
Convert Based Numbers to ints
Write a general function that expects a string representation of a number and its base (an int) as arguments The function returns the integer represented >>> repToInt('10', 2) # 102 = 2 2 >>> repToInt('10', 10) # 1010 = 10 10 >>> repToInt('10', 16) # 1016 = 16 16 >>> repToInt('100', 2) # 1002 = 4
6
Implementation def repToInt(digits, base):
"""Returns the integer represented by the digits in the given base.""" intValue = 0 expo = len(digits – 1) for ch in digits: ch = string.upper(ch) intvalue += hexdigits[ch] * base ** expo expo -= 1 return intValue
7
Default and Optional Parameters
One or more parameters can have default values, so the caller can omit some arguments >>> repToInt('111', 2) 7 >>> repToInt('111', 10) 111 >>> repToInt('111', 16) 273 >>> repToInt('111') # Same result as the previous line The caller can treat base16 as the standard base in this system or use other bases by mentioning them
8
Implementation def repToInt(digits, base = 16):
"""Returns the integer represented by the digits in the given base.""" intValue = 0 expo = len(digits – 1) for ch in digits: ch = string.upper(ch) intvalue += hexdigits[ch] * base ** expo expo -= 1 return intValue
9
Some Syntax Rules The required arguments used in a function call must match the required parameters named in the definition, by position The programmer should list the required parameters first (to the left) in the function’s definition def <function name>(<required params>, <default params>):
10
Some Syntax Rules A required parameter is just a name
A default parameter looks like an assignment statement def <function name>(<name>,…, <name> = <expression>,…):
11
Section 6.6 Higher-Order Functions
For Wednesday Section 6.6 Higher-Order Functions
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.