110 likes | 223 Views
More Advanced Functions. What is a Function. A named sequence of statements Perform some task May take parameters May return values. Example. def getInput () : x = int (input (‘Enter a positive number ’)) if (x < 0) : print(x , ‘ is not a positive number !’) getInput ().
E N D
What is a Function • A named sequence of statements • Perform some task • May take parameters • May return values
Example defgetInput() : x = int(input(‘Enter a positive number’)) if (x < 0) : print(x, ‘ is not a positive number!’) getInput()
Returning Values • Local variables and parameter variables lost when function completes. • To keep the values, have to copy them to other variables. • Save the value by returning them from the function • Store the value by assigning function value to variable(s)
Example with Return defgetInput() : x = int(input(‘Enter a positive number’)) return x num= getInput()
Program Development • Determine functions to write • Write and test one at a time • Write each function incrementally • Write a few statements • Test • Repeat until function is complete
Example • Write a program that prompts the user for a number between 1 and 10 and displays the Roman numeral version of the number.
Boolean Functions • Functions can return data of type boolean • Boolean functions can be used in conditions • Often make conditions easier to read
Example – Boolean Functions • Take as input any integer and print if the number is even or odd.
Recursion Revisited defgetInput() : x = int(input(‘Enter a positive number’)) if (x < 0) : print(x,‘isnot a positive number!’) num = getInput() else : num = x return num
Returning Multiple Values • What if we need to return more than one value from a function? • Comma separated list of values in return statement • Comma separated list of variables to the left of the equals sign