Python Scripts and Values
Values have types
Section titled “Values have types”Programs do not treat 12 and "12" as the same value. The first is an integer suitable for arithmetic. The second is a string containing two characters. A type describes what kind of value something is and which operations make sense for it.
Create values.py:
count = 12label = "files"complete = False
print(type(count), count)print(type(label), label)print(type(complete), complete)Run it with python3 values.py. A variable is a name bound to a value; it is not a box permanently restricted to one kind of value. Python tracks the value’s type at runtime.
Change count to "12", predict what count + 3 will do, then try it. The resulting TypeError tells you the operation and incompatible types. Restore the integer afterward.
Input begins as text
Section titled “Input begins as text”Create arguments.py:
import sys
print("program:", sys.argv[0])print("arguments:", sys.argv[1:])Run:
python3 arguments.py alpha 27sys.argv is a list of strings. Index zero identifies the script; later entries contain supplied arguments. Even 27 arrives as text.
Convert deliberately:
import sys
count = int(sys.argv[1])print("next:", count + 1)Try no argument, 12, and twelve. Record the IndexError and ValueError. Each failure identifies a different unsupported assumption.
Knowledge check
Question 1 of 2
Knowledge check complete
You answered all 2 questions correctly.
What this gives us as researchers
Section titled “What this gives us as researchers”You can identify values entering a program, track their types, and recognize the assumptions introduced by conversion. Next we will follow those values through decisions and repeated work.