Skip to content

Commit 93ac670

Browse files
committed
Merge branch 'master' of https://github.com/HamPUG/examples
2 parents fa8d31a + b1e1a58 commit 93ac670

21 files changed

+6445
-0
lines changed

ncea_level2/templates/README.md

+169
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
## Code Templates in Python - Level 2
2+
3+
These code templates may be useful for anyone who is learning the Python programming language. The templates use the procedural programming style. These templates are numbered and they are associated with the same numbered programs in the [snippets folder](https://github.com/HamPUG/examples/tree/master/ncea_level2/snippets).
4+
5+
The top and bottom of these template programs remains much the same for each program. At the top of each program the template provides: shebang, importing modules, program description, copywrite, defining constants and variables. At the bottom of each program the template provides: `if __name__ == '__main__':`, help information function, python version check function, log file append function, command line argument parsing including debugging and help flags, and calls the main() function.
6+
7+
The middle section of these template programs is what changes to give each program its unique features. It contains a main() function which includes calls to other functions.
8+
9+
These template programs highlight the use of function code blocks, but do not utilise classes. They also assume the program is written as one file, and importing of modules is restricted to a small set of the builtin python modules.
10+
11+
The programs are all console terminal based and there is no use of GUI windowing.
12+
13+
These templates were developed using Python 3.4. They have been tested on Ubuntu Linux and Windows10 desktop environments.
14+
15+
New Zealand secondary school teachers and students may find these template useful for the Digital Technologies, Level 2, Achievement Standards [91372](http://www.nzqa.govt.nz/nqfdocs/ncea-resource/achievements/2017/as91372.pdf) and [91373](http://www.nzqa.govt.nz/nqfdocs/ncea-resource/achievements/2017/as91373.pdf).
16+
17+
In a classroom computer lab that uses Windows10 desktop computers, the console terminal window applications (CMD and Powershell) may have been made unavailable on the students desktop computers. In the Windows10 file manager, if a *python* file is double-clicked it will launch a terminal window to run the python program. When the program completes, this terminal window is closed. To prevent the programs closing before a student has been able to see what the program does, all these snippet programs end with the lines...
18+
19+
input("Press Enter key to end the program.")
20+
sys.exit()
21+
22+
Ian Stewart - 2016 © [![](https://licensebuttons.net/l/by/4.0/80x15.png)](https://creativecommons.org/licenses/by/4.0/)
23+
24+
## Template Programs
25+
26+
**template_l2_01.py** - *Fundament_Components*
27+
28+
Python program. Fundamental programming style components.
29+
Includes: Shebang, encoding, Commented text in help(),
30+
Importing modules, variables, constants, python2 check,
31+
main function, cli help(), `if __name__ == '__main__':`,
32+
cli sys.argv list, debug, call main()
33+
34+
**template_l2_02.py** - *Time-Stamped_Logging*
35+
36+
Python program using a procedural programming style.
37+
Add Logging of time-stamped data
38+
39+
**template_l2_03.py** - *Check_Python_Min_Version*
40+
41+
Python program using a procedural programming style.
42+
Add: Check python is above the minimum version.
43+
44+
**template_l2_04.py** - *Functions*
45+
46+
Python program using a procedural programming style.
47+
Add: 2 x functions. Includes data-type testing and +=1
48+
Data can be passed as a command line option.
49+
50+
**template_l2_05.py** - *Input_From_Console*
51+
52+
Python program using a procedural programming style...
53+
Get integer or floating point value from console.
54+
55+
**template_l2_06.py** - *Input_Integer_From_Console*
56+
57+
Python program using a procedural programming style...
58+
Add: Integer only data from console.
59+
60+
**template_l2_07.py** - *Circle_Calculator*
61+
62+
When provided with the a value for the radius, the circle
63+
calculator program will determine the circles
64+
circumference and area.
65+
66+
**template_l2_08.py** - *Sphere_Calculator*
67+
68+
When provided with the a value for the radius, the sphere
69+
calculator program will determine the spheres
70+
surface area and volume.
71+
72+
**template_l2_09.py** - *Cube_Calculator*
73+
74+
When provided with the length of the edge of a cube
75+
calculator program will determine the cubes
76+
surface area, volume, and space diagonal.
77+
78+
**template_l2_10.py** - *Circle_Plotter*
79+
80+
When provided with a range of integer values for a radius
81+
the circle plotter program will determine the
82+
diameter, circumference and area.
83+
The output may be cut and pasted into a spreadsheet.
84+
If so, space delimiters must be merged.
85+
86+
**template_l2_11.py** - *Sphere_Plotter*
87+
88+
When provided with a range of integer values for a radius
89+
the sphere plotter program will determine the
90+
circumference, surface area and volume.
91+
The output may be cut and pasted into a spreadsheet.
92+
If so, space delimiters must be merged.
93+
94+
**template_l2_12.py** - *Sphere_Volume_Plotter*
95+
96+
When provided with a range of integer values for the
97+
cubic meter volume of a sphere, the sphere volume plotter
98+
program will determine the radius, diameter and
99+
circumference of the sphere in meters.
100+
The output may be cut and pasted into a spreadsheet.
101+
If so, space delimiters must be merged.
102+
103+
**template_l2_13.py** - *Sphere_Litre_Plotter*
104+
105+
When provided with a range of integer values for the
106+
litres a sphere will hold, the sphere litre plotter
107+
program will determine the radius, diameter and
108+
circumference of the sphere in centimeters.
109+
The output may be cut and pasted into a spreadsheet.
110+
If so, space delimiters must be merged.
111+
112+
**template_l2_14.py** - *Circle_Plotter_CSV*
113+
114+
When provided with a range of integer values for a radius
115+
the circle plotter program will determine the
116+
diameter, circumference and area. Like template_l2_10.py
117+
The data is output to a comma seperated values (.csv) file.
118+
119+
**template_l2_15.py** - *Cube_Plotter_CSV*
120+
121+
When provided with the length of the edge of a cube
122+
calculator program will determine the cubes
123+
surface area, volume, and space diagonal.
124+
Similar to template_l2_09.py
125+
The data is output to a comma seperated values (.csv) file
126+
The function update_data() is called from main().
127+
128+
**template_l2_16.py** - *Fibonacci_sequence*
129+
130+
Generate the Fibonacci sequence of integers.
131+
The total for the sequence may be selected.
132+
As each Fibonacci number in the sequence is generated
133+
it is appended to a list.
134+
The items in the list are then output to the console.
135+
The sequence has been limited to 200 so they are easier
136+
to read on the console.
137+
Highlights there is no limit to python integer arithmetic
138+
139+
**template_l2_17.py** - *Integer_Fun*
140+
141+
Demonstrate the arithmetic performed on integers is
142+
accurate and has no limits.
143+
Starting with a funny number it is manipulated with
144+
multiplication (*), addition (+) and exponents (**) to
145+
create an integer that is comprised of only one's.
146+
Also highlights use of the modulo operator (%) and pythons
147+
integer division (//), which is floor division.
148+
149+
**template_l2_18.py** - *Integer_Distance*
150+
151+
Demonstrate the arithmetic performed on integers is
152+
accurate and has no limits.
153+
Introduce floating point calculation.
154+
155+
**template_l2_19.py** - *Bike_Speed*
156+
157+
Determine the speed of a bicycle. Parameters that may be
158+
adjusted are:
159+
1. Diameter of the rear wheel.
160+
2. Cadence. The revolutions per minute of the pedalling.
161+
3. Crankset teeth. Number of teeth on the front sprocket.
162+
A list provides the number of teeth on each sprocket of
163+
the casette on the rear wheel.
164+
Input values are Integers. Calculations are mostly floats.
165+
166+
**template_l2_20.py** - *Floating_Point*
167+
168+
Demonstrate floating-point arithmetic and
169+
highlight some of its issues and limitations.
+166
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
#
4+
# template_l2_01.py based on template_master_l2.py
5+
# Introduces: Shebang, encoding, Commented text in help(), Importing modules,
6+
# variables, constants, python2 check, main function, cli help(),
7+
# if __name__ == "__main__":, cli sys.argv list, debug, call main()
8+
#
9+
# TODO: Describe your program here so that its description will be displayed
10+
# using help(). See pydocs https://docs.python.org/3/library/pydoc.html
11+
# E.g. $ pydoc3 -p 1234 then in a browser http://localhost:1234/
12+
13+
# Template functions utilize modules. Import them now to avoid problems later.
14+
# import modules # Functions, Strings, Lists used in template:
15+
import sys # .version(), .hexversion(), .exit(), .argv .stdout.write()
16+
# # .stdout.flush()
17+
import os # .sep, .getcwd()
18+
import datetime # .datetime.now().strftime() .datetime.utcnow().strftime()
19+
# # .datetime.today()
20+
import textwrap # .TextWrapper()
21+
import tempfile # .TemporaryFile(), .gettempdir()
22+
import time # .time(), .sleep()
23+
import locale # .setlocale(), .currency()
24+
25+
# Modules that could be handy...
26+
import decimal
27+
import math
28+
import random
29+
30+
# Program details variables.
31+
_program_ = "Fundament_Components" # "template_l2_01.py"
32+
_version_ = "1.0"
33+
_date_ = "2016-10-25"
34+
_author_ = "Ian Stewart"
35+
_copyright_ = "© https://creativecommons.org/licenses/by/4.0/"
36+
_description_ = ("Python program. Fundamental programming style components.\n"
37+
"Includes: Shebang, encoding, Commented text in help(), \n"
38+
"Importing modules, variables, constants, python2 check, \n"
39+
"main function, cli help(), if __name__ == '__main__':, \n"
40+
"cli sys.argv list, debug, call main()")
41+
42+
_original_ = ("template_master_l2.py - Ian Stewart - October 2016.\n"
43+
"© https://creativecommons.org/licenses/by/4.0/")
44+
45+
# Global Constants and variables init values. Can be read within functions.
46+
# Can be the default values for arguments of a function.
47+
PYTHON_MIN_VERSION = "3.2"
48+
debug = False
49+
log = "log_{}.txt".format(_program_)
50+
stuff = 42
51+
input_file = "./temp/some_data.txt"
52+
output_file = "./temp/some_data.txt"
53+
timer_activated = 0
54+
55+
# Global variables that could be handy...
56+
sep = os.sep
57+
cwd = os.getcwd() + sep
58+
59+
# Check python is not below version 3. Prohibit running version 2.
60+
if int(sys.version[:1]) < 3:
61+
print("Python version {} is not supported. \n"
62+
"Please restart using Python version 3 or higher. Exiting..."
63+
.format(sys.version.split(" ")[0]))
64+
sys.exit()
65+
66+
67+
def main(data=stuff, log=log, in_file=input_file, out_file=output_file):
68+
"""
69+
Main function that calls all other defined functions and statements.
70+
Edit this function to make your program...
71+
"""
72+
if debug: print("Program is starting...")
73+
if debug: print("data: {}, logfile: {}".format(data, log))
74+
if debug: print("in_file: {}, out_file: {}".format(in_file, out_file))
75+
#
76+
# Call functions here...
77+
print("Main function is executing. It would normally call other functions")
78+
print("The program will sleep for 5 seconds")
79+
# Do nothing for 5 seconds...
80+
time.sleep(5)
81+
82+
print("Finished sleeping.")
83+
if debug: print("Program is finished.")
84+
input("Press Enter key to end program.")
85+
sys.exit()
86+
# ===== end of main function =====
87+
88+
# Add more functions here...
89+
90+
91+
def help():
92+
"Provide help on command line options available."
93+
print("Program: {0}, Version: {1}, Date: {2}, Author: {3}"
94+
.format(_program_, _version_, _date_, _author_))
95+
print("{}".format(_description_))
96+
print("Usage: {} [OPTION]".format(_program_))
97+
print("Arguments...")
98+
print(" -h, --help Provide this help information.")
99+
print(" -d, --debug Provide additional information \n"
100+
" during program development.")
101+
print(" -i=, --input=[FILE] Input file")
102+
print(" -o=, --output=[FILE] Output file")
103+
print(" -s=, --stuff=[VALUE] Assign a value to stuff")
104+
print(" -l=, --log=[FILE] Provide a filename for logging")
105+
print("")
106+
print("Copyright: {}\n".format(_copyright_))
107+
108+
109+
if __name__ == "__main__":
110+
# Get command line options from sys.argv list
111+
for index, option in enumerate(sys.argv):
112+
if "-h" in option:
113+
help()
114+
sys.exit()
115+
116+
if "-d" in option:
117+
debug = not debug
118+
119+
# Collect string data from command line interface (cli) sys.argv list
120+
# Overide "stuff" global variable.
121+
# Use = as the delimiter to split keyword and value. E.g.
122+
# -s=1, --stuff=2, -s=" Has spaces ", --stuff=Smith, -s=4=four, etc.
123+
if "-s" in option:
124+
stuff_list = sys.argv[index].split("=")
125+
if len(stuff_list) > 1:
126+
stuff = stuff_list[1]
127+
128+
if "-i" in option:
129+
input_list = sys.argv[index].split("=")
130+
if len(input_list) > 1:
131+
input_file = input_list[1]
132+
133+
if "-o" in option:
134+
output_list = sys.argv[index].split("=")
135+
if len(output_list) > 1:
136+
output_file = output_list[1]
137+
138+
# Provide for a log file. Changes file name assigned to "log" variable.
139+
if "-l" in option:
140+
log_list = sys.argv[index].split("=")
141+
if len(log_list) > 1:
142+
# Avoid complexity of log file in sub-directories. In cwd.
143+
if os.sep not in log_list[1]:
144+
log = log_list[1]
145+
146+
if debug: print("sys.argv list = {}".format(sys.argv))
147+
if debug: print("Variables: debug:{}, stuff:{}, log:{}, input_file:{},"
148+
"output_file:{}"
149+
.format(debug, stuff, log, input_file, output_file))
150+
151+
# Call main program, pass values from command line arguments, or variables
152+
# with their default values which may not have been modified by the cli.
153+
main(stuff, log, input_file, output_file)
154+
155+
"""
156+
Notes:
157+
158+
To check code style:
159+
Linux...
160+
$ python3 -m pep8 --statistic --ignore=E701 template_l2_01.py
161+
Install pep8 on Linux: $ sudo apt-get install python3-pep8
162+
Windows...
163+
> python -m pep8 --statistic --ignore=E701 template_l2_01.py
164+
Install pep8 on Windows: >pip3 install pep8
165+
More information: https://www.python.org/dev/peps/pep-0008/
166+
"""

0 commit comments

Comments
 (0)