Open main menu

CDOT Wiki β

Changes

OPS435 Python Lab 3

42 bytes added, 10:11, 2 June 2017
PART 2 - Creating a Python Script with Functions and Importing Functions
The IF statement in the code displayed in the previous section is considered to be a '''special IF statement'''. It allows '''variables''' and '''functions''' from other python scripts to be '''used in your current Python script (or in the ipython shell) without having to re-define those functions'''. In order to use functions from other scripts, you are required to either issue the import command in your ipython3 shell environment, or use the import command within your Python script itself.<br><br>We can demonstrate the use of re-using functions from another script by simply '''issuing statements from the ipython shell by calling a function that is related to your lab3a.py Python script'''. But care MUST be taken to first use the import command to load in the function declarations from your Python script to your ipython shell environment first.<br><br>
 :'''Perform the following Instructions:''' :3. # Let's see what happens if we forget to import functions from your lab3a.py script prior to calling a function. Issue the following:<source>
text = lab3a.return_text_value()
</source>You should notice an error indicating '''"name 'lab3a' is not defined"'''. This error occurs since you failed to instruct the ipython shell to '''import''' or "load existing defined functions from your lab3a.py script" to '''internal memory'''.<br><br>
:::4. # Issue the following within the ipython shell:<source>
import lab3a
text = lab3a.return_text_value()
lab3a.return_number_value()
</source> You should notice that all of the function calls should now work. '''NOTE:''' since you are in the ipython shell, the import command only will work as long as you are '''logged into that shell'''. You will need to use other methods (contained in other Python Scripts (or future ipython shell sessions) to make these function imports '''persistent''', but you will learn about that at a later time.<br><br>
:::5. # Exit the ipython3 shell, download the checking script and check your work. Enter the following commands from the bash shell.<source>
cd ~/ops435/lab3/
pwd #confirm that you are in the right directory
python3 ./CheckLab3.py -f -v lab3a
</source>
:::6. # Before proceeding, make certain that you identify any and all errors in lab3a.py. When the checking script tells you everything is OK before proceeding to the next step.
::Make notes for all of your observations in your lab log book, and proceed to Part INVESTIGATION 2.
<br><br>
13,420
edits