1 / 11

More Advanced Functions

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 ().

trynt
Télécharger la présentation

More Advanced Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. More Advanced Functions

  2. What is a Function • A named sequence of statements • Perform some task • May take parameters • May return values

  3. Example defgetInput() : x = int(input(‘Enter a positive number’)) if (x < 0) : print(x, ‘ is not a positive number!’) getInput()

  4. 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)

  5. Example with Return defgetInput() : x = int(input(‘Enter a positive number’)) return x num= getInput()

  6. 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

  7. Example • Write a program that prompts the user for a number between 1 and 10 and displays the Roman numeral version of the number.

  8. Boolean Functions • Functions can return data of type boolean • Boolean functions can be used in conditions • Often make conditions easier to read

  9. Example – Boolean Functions • Take as input any integer and print if the number is even or odd.

  10. 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

  11. 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

More Related