Changes

Jump to: navigation, search

OPS435 Python3 Lab 7

527 bytes added, 21:52, 3 November 2019
Part 2: Global Scope
: Sometimes you want to have an object accessible from anywhere in your program, including inside and outside any functions. Here's an example:
:1. '''[https://ict.senecacollege.ca/~raymond.chan/ops435/labs/lab7/lab7h.py lab7h.py]''' - global scope <source lang="python">
#!/usr/bin/env python3
# Student ID: [seneca_id]
</source>
: 2. Note that the same thing is printed over and over because the '''schoolName''' object is defined outside a function which makes it global which makes it accessible from anywhere.
: 3. Python has one weird quirk when it comes to global scope: if you assign something to an existing object inside a function - it will assume you want to create a new object in that function's local scope. That will hide the global object inside the function unless you declare it explicitly with the global keyword:: 4. '''[https://ict.senecacollege.ca/~raymond.chan/ops435/labs/lab7/lab7i.py lab7i.py]''' - global keyword <source lang="python">
#!/usr/bin/env python3
# Student ID: [seneca_id]
print('print() in main on schoolName:',schoolName)
</source>
:* The execution of the script '''lab7i.py''' shown above should give youryou the following:<source lang="bash">
[rchan@centos7 lab7]$ python3 lab7i.py
print() in main on schoolName: Seneca
print() in main on schoolName: SSDO
</source>
::*Note that the function1() call does not modify the global '''schoolName''' object but function2() does.
: 5 As the last task for this lab: modify the script above so that it would print the following, by changing only the scope of some objects. Save the program as '''lab7i.py''': <source lang="bash">
print() in main on schoolName: Seneca
print() in function1 on schoolName: SICT
print() in main on schoolName: SSDO
</source>
 
:6. Download the checking script and check your work. Enter the following commands from the bash shell.<source lang="bash">
cd ~/ops435/lab7/
pwd #confirm that you are in the right directory
ls CheckLab7.py || wget https://ict.senecacollege.ca/~raymond.chan/ops435/labs/LabCheckScripts/CheckLab7.py
python3 ./CheckLab7.py -f -v lab7i
</source>
:7. Before proceeding, make certain that you identify all errors in lab7i.py. When the checking script tells you everything is OK - proceed to the next step.
== Object/Instance Scope ==
1,760
edits

Navigation menu