Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1.

Similar presentations


Presentation on theme: "Introduction to Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1."— Presentation transcript:

1 Introduction to Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1

2 What is a Function? function code

3 Modular Programming Modular programming: Creating program as a set of functions instead of one big code listing Why? Easier to implement and test one function at a time Complex code more readable and understandable as functions Easier to reuse code (and share with other programmers) – Can implement functions in a module in a separate file – Other programmers can then import that module

4 Example: Fahrenheit to Celsius

5 Function Definition Syntax def function_name(arguments): statement statement … return value arguments : List of variable names that values in call are assigned into return value : Value returned from function (what function call “evaluates” to) Note: function body indented to indicate where it ends

6 Invoking Functions Program starts at beginning of “non-function” code – “Main program” Continues until function call reached Arguments in function call evaluated and “passed” to function – Example: User enters 45 for f – Value of f (that is, 45) passed to function

7 Invoking Functions Values passed assigned into corresponding variables in function arguments – fahrenheit_temperature assigned 45 Code in function executed one line at a time until a return statement reached Expression in return evaluated and sent back to caller – 7.222222 returned in this case

8 Invoking Functions Function call evaluates to value returned – fahrenheit2celsius(f) evaluates to 7.222222 Main program continues on from that point

9 Function Calls Can call same function multiple times with different arguments – Easier to write that code once in function instead of writing code multiple times in main program – One of main reasons to create functions Example: Finding largest of four numbers – Compare first two to find larger – Compare second two to find larger – Compare those to then find overall largest Idea: Write code for finding larger of 2 numbers once Call three times from main program

10 Example: max function

11 Can nest complex code inside function definition – Must indent branches, loops further Can have multiple return statements in function definition – Function exits back to caller when first one executed


Download ppt "Introduction to Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1."

Similar presentations


Ads by Google