Open main menu

CDOT Wiki β

Changes

OPS435 Python Lab 3

797 bytes removed, 22:04, 27 January 2018
PART 2 - Creating a Python Script with Functions and Importing Functions
print(str(number))
</source>
:::2. Run Running your lab3a.py script in your ipython3 shell by issuing:<source>run lab3a.py</source>You program you should have seen three lines being displayed: the text "python code", a greeting, and a result of a math calculation. The '''if''' statement in the code above is a special '''if''' statement needed to make sure that your "main" code only runs when you want it to. More on that later.
'''Importing Functions From other Python Scripts'''
In order to use functions from other scripts, you use the '''import''' command.<br><br>We can demonstrate the use of re-using functions from another script by simply '''issuing statements from the ipython shell to call a function from 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 firststatement.<br><br>
:'''Perform the following Instructions:''' :# Let's see what happens if we forget to import functions from your lab3a.py script prior to calling a function. Issue Create a new python file and try to call the followingreturn_text_value() function:<source lang="python">
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 python to '''import''' or "load existing defined functions from your lab3a.py script" to '''internal memory'''.<br><br>:# Issue the following within the ipython shellModify your program like this:<source lang="python">
import lab3a
text = lab3a.return_text_value()
text
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>:# Exit the ipython3 shell, download Download the checking script and check your work. Enter the following commands from the bash shell.<source lang="bash">
cd ~/ops435/lab3/
pwd #confirm that you are in the right directory