Skip to content

Commit d95da36

Browse files
author
James Collier
committed
Add a "scripting" reading exercise
1 parent b7255f5 commit d95da36

2 files changed

Lines changed: 63 additions & 0 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"description": {
3+
"names": {
4+
"en": "Scripting"
5+
}
6+
},
7+
"labels": [
8+
"real-world programming"
9+
],
10+
"internals": {
11+
"token": "X5rVj9e4R7tbj4SxX78RXrS93eTq5CkKfT6HWTJrer2I-N33yqry9dj-nSRfzHct",
12+
"_info": "These fields are used for internal bookkeeping in Dodona, please do not change them."
13+
}
14+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
When you write a program for yourself (or download a Python program from the internet), you will
2+
probably want to run it sooner or later.
3+
4+
This is quite straightforward. You can simply follow these steps:
5+
* Open the terminal program you use (on Windows this might be called "Power Shell" or "CMD"),
6+
* Navigate to the folder where the program is stored,
7+
* Run the program by typing `python my_cool_program.py` (also known as running a "script").
8+
9+
There is an important problem when building programs that you should be aware of: any top-level code
10+
always runs when you run the script **BUT ALSO** at _import_ time. That's right! You can `import`
11+
your program too.
12+
13+
This is a problem because, you probably don't expect to be running Python code just because you
14+
`import`ed something. To avoid this you can use a trick to check if your code is being run as a script
15+
or if it's being imported.
16+
17+
There is a special variable that Python gives you called `__name__` which is the name of the current
18+
module. Try this in your own programming environment if you like: create 2 files.
19+
20+
A file "a.py" should contain:
21+
```python
22+
print("__name__ is: ", __name__)
23+
```
24+
25+
A file "b.py" should contain:
26+
```python
27+
import a
28+
print("I'm in b")
29+
```
30+
31+
Now run `python a.py` (Use a.py as a script, not importing it). This should be printed to the console:
32+
```
33+
__name__ is: __main__
34+
```
35+
36+
And if you run `python b.py` (Import a.py). This should print:
37+
```
38+
__name__ is: a
39+
I'm in b
40+
```
41+
42+
Notice that the special variable `__name__` contains `"__main__"` when you run the file as a script.
43+
So when you define code to run when using your program as a script you should use this construction:
44+
```python
45+
if __name__ == "__main__":
46+
# code to run when using my program as a script.
47+
48+
```
49+

0 commit comments

Comments
 (0)