Changes

Jump to: navigation, search

OPS435 Python3 Lab 3

327 bytes added, 16:48, 19 September 2019
PART 2 - Creating a Python Script with Functions and Importing Functions
</source>
== PART 2 4 - Creating a Python Script with Functions and Importing Functions use them in anther Python script==
'''Creating a Python Script'''
:Now it's time to create a Python script that uses defines two functions. One function returns a string value to greet the user, where the other function returns the result of adding two values (the two values are stored in variables within the functionas integer objects).
:'''Perform the following Instructions:'''
:::*The script should have a '''Shebang line'''
:::*Below the '''Shebang line''', add an '''empty line''' followed by a comment stating: '''# return_text_value() function'''
:::*Add an '''comment line''' and put the string '''Author ID:''' followed by your [seneca_id] in that line:::*Add an '''empty line''' followed by the '''return_text_value()''' function '''definition''' that you previously entered in the shellpart 3.
:::*Add another '''empty line''' followed by a comment stating: '''# return_number_value() function'''
:::*Add another '''empty line''' following by the '''return_number_value()''' function '''definition''' that you previously entered in the shell.
print(str(number))
</source>
:Running your 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 your script is executed by the Python interpreter directly, and will be ignored when you want it topython file is being imported by other script, or by an interactive python shell. More on that later.
'''Importing Functions From other Python Scripts'''
:# Let's see what happens if we forget to import functions from your lab3a.py script prior to calling a function. Create a new python file and try to call the return_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 python to '''import''' or "load existing defined functions from your lab3a.py script" to your new running python script's '''internal process memory'''.<br><br>:# Modify your program script like this:<source lang="python">
import lab3a
text = lab3a.return_text_value()
cd ~/ops435/lab3/
pwd #confirm that you are in the right directory
ls CheckLab3.py || wget https://rawict.githubusercontentsenecacollege.comca/Seneca-CDOT~raymond.chan/ops435/masterlabs/LabCheckScripts/CheckLab3.py
python3 ./CheckLab3.py -f -v lab3a
</source>
1,760
edits

Navigation menu