Changes

Jump to: navigation, search

OPS435 Python Lab 3

228 bytes removed, 19:53, 9 August 2017
INVESTIGATION 1: CREATING SIMPLE FUNCTIONS
= INVESTIGATION 1: CREATING SIMPLE FUNCTIONS =
:A very simple definition of using '''functions''' is to create and reuse '''smaller programs within a larger program'''. In programming languages such as '''C''', '''C++''' and '''Java''', commonly used functions are pre-packaged in '''Librarieslibraries'''. This relates to dependency issues that were discussed when compiling C programming code in your OPS25 OPS235 course: if a supporting library is missing, the program would be able to run the called function. We do not go into detail involving Libraries for this course since Python is an '''interpreted''' (i.e. not a compiled) language.
:Usually, a '''function''' will '''contain programming code''' in some part of the main program python file (most likely near the '''top''' of the program '''BEFORE''' file, before the main program). We refer to that as a '''"function declaration"'''.: When a program is run, the '''function's code is read into internal memory''', ready to be run when the function is '''run''' executed (referred to as '''calling the function'''). Until a Function is specifically told to execute, it's its code will sit (in internal memory) unused.
:When creating programs that define and use functions, '''a large programming task can be broken-down into smaller elements''' (or '''modules'''). This is why creating programs that use functions is referred to as '''"modular programming"'''.
:#To start, open the ipython3 shell:<source>
ipython3
</source>Whenever you want to create a function, you must start with the keyword "'''def'''". The '''def''' keyword is used to start the definition of the function, it does not run the code you write. Functions, just like '''if ''' statements, must have all code under them indented.<br><br>
:# Enter the following code in your ipython3 shell:<source>
def hello():
print('Hello World')
print('Inside a Function')
</source>Remember to press '''ENTER''' a second time to return to the ipython prompt. You may have notices noticed that nothing happened. Well actually, something did happen... the function called '''hello(''') has been defined and stored in internal memory in order for it to run when called by its function name. Now that our function was created, we can use it over and over. <br><br>
:#To execute the code inside the function, run the function name with "'''()'''" '''brackets''' at the end of the function name.<br>Try running the '''hello()''' function by name three times by issuing the following in the ipython3 shell:<source>
hello()
print('my number is ' + str(return_number_value()))
</source>
 
::Make notes for all of your observations in your lab log book, and proceed to Part 2.
== PART 2 - Creating a Python Script with Functions and Importing Functions ==

Navigation menu