Unit 1: Getting Started with Python
Skill Builder 1: Introducing the Python AppsDownload Teacher/Student Docs
In this lesson, you will be introduced to the Python programming system on the TI-84 Plus CE Python edition graphing calculator. You will take a tour of the menus, explore the changes to the keypad, and work with a program to see some of the key features of using Python.
- Python overview
- Use Editor and Shell
- Run a program
- Edit a program
- Entering expressions in the Shell
Welcome to the Python experience on your TI-84 Plus CE Python graphing calculator. These lessons require no prior knowledge of programming and will help you get started with coding in Python in a friendly, easy-to-use platform in the palm of your hand. Get ready to tap the power of programming in Python.
Let’s start learning about the Python environment. Press [prgm] and select Python App from the menu.
The Python App is now active. You are looking at the FILE MANAGER showing the Python files the that are stored in RAM in your calculator. As you add programs, their filenames will be added to this short list alphabetically.On the bottom of the screen is a custom menu bar (“soft keys”). Access these menus by pressing the corresponding top-row key on your keypad. In these lessons you will see
… select<menu_name> …
and not the corresponding key name. For example:
To run the HELLO program, press the [down arrow] key to
point to the word HELLO and select <Run> or press [enter].
Select <Run> by pressing [y=].Note that the on-screen menu item <Softkey> is preceded by “select…” and a keypad key is preceded by “press…”. This distinction is used throughout all these lessons and the corresponding top-row key will not be stated in the text. Also note that all the on-screen menus begin with a capital letter (but not menu items), and keypad keys are all lowercase.
Running the HELLO program brings you to the Python Shell, the place where Python programs are run. The Shell prompt is >>>. The program displays a TIp and the question “What is your name?” You must type your name and press [enter].
Note: TIp is no accident. After all, this is Texas Instruments!
To type letters, press [2nd] [alpha] to turn on lowercase alpha-lock, then type the letters. If you want capital letters, press the [alpha] key again.
Tip: The [alpha] key toggles between lowercase and uppercase modes. See the current state at the top of the screen. In this image, lowercase alpha-lock is active.
At the end of your name, press [enter] to see what the program produces (“Hello name” and another TIp).
Press [2nd] [alpha] to turn alpha-lock off.
When you see >>> | the program has ended. The symbol >>> is the Shell prompt and the vertical bar ( | ) is the cursor.
At the Shell prompt >>> you are free to type some Python expressions. The Shell is similar to the calculator HOME screen, but it only understands Python expressions.
Try some calculations (press [enter] on each line to see the effect):
>>>5 * 5
>>>6 * (4 - 2)
>>>3 ** 5 (raise to a power: 35; use [^] for **)
>>>x = 13 (assign 13 to x; use the [sto] key for =)
>>>2 * x + 4
After each expression except x=13 you will see the result displayed.
The keypad is very different when working in Python. The top (graphing) row is used for accessing the Python menus on the bottom of the screen. Python supports both lowercase and uppercase characters. Many keys are now “python-friendly” (like [^] and [sto]). The cursor is a vertical bar in the Shell and a blinking underscore (insert mode only) in the Editor. Pressing [del] performs a backspace operation, deleting the character to the left of the cursor. Other keys take on new meanings as you will see.
In the next step you will have a look at the Python [Editor] containing the HELLO program.
Note that the [X,T,θ,n] key now produces the either lowercase x or uppercase X depending on the alpha
Select <Editor> (press the [trace] key). You are now using the Python Editor which is where programs are written and edited. The menu at the bottom of the screen is slightly different: [Run] replaces [Editor].
The Editor is color-enhanced.
The program contains print( ) statements and one input( ) function:
n = input (“What is your name?”)
The top line is a comment: # Version 2 EN. It begins with the # sign. Comments are useful to add notes to your code that the Python interpreter ignores when the program is run.
The “green” stuff is text in quotation marks.
The red \n is a special “newline” character.
Note: Feel free to edit the program but be aware that all changes you make are automatically saved. You will write your own code in the next lesson.
Explore the other menus at the bottom of the screen, using the top row of keys on the calculator.
[Fns…] contains seven sub-menus across the top of the screen. These sub-menus contain all the Python programming commands.
The Func menu shown has just two statements but the others have many more.
In the lower left corner is the <Esc> option which takes you back to the Editor or Shell when you press the [y=] key.
We will explore the other sub-menus as we begin to write our own programs.
Select <Esc> at any time to return to the Editor.
Did you press the [y=] key? Congratulations! From now on we will use the language Select <menu option> to refer to the menu bar at the bottom of the screen and you will press the corresponding top-row key.
The FILE MANAGER displays the Python files that are stored in RAM on your calculator. The menu bar displays:
<Run> — run the program you are pointing at
<Edit> — load the program into the Editor
<New> — create a new Python file
<Shell> — bring up an empty Shell
<Manage> — manage your files (Copy, Delete, Rename)
The calculator comes with two other demo programs: GRAPH and LINREGR. Feel free to run them at any time but be careful about editing them.
To quit using Python and return to your calculator’s home screen, press [2nd] [mode] ([quit]) or, in the FILE MANAGER, select <Manage> and choose Quit Python.
You will see this “Are you Sure?” screen. Select <Ok> or press [enter] to quit.
Note: Any file that you are working on is automatically saved as you type. There is no need to save your Python file. Tip: When done with Python, do not leave the Editor on the screen as it immediately responds to key presses and can mess up the program that is on the screen. You can leave it on the Shell or FILE MANAGER or you can quit the Python App completely.
If you have written programs using TI-Basic, these are some of the BIG differences between TI-Basic and Python:
- Lowercase is the norm in Python and Python is case-sensitive
- Character-by-character typing is allowed; rather than selecting print() from a menu, you can simply type it in
- Python relies heavily on proper indentation to determine code blocks like loops and if… blocks rather than keywords or symbols; the Editor has special indentation symbols (gray diamond characters) to help manage indentation
In the next lesson, you will write your own program.
Skill Builder 2: Editing, Variables, ExpressionsDownload Teacher/Student Docs
In this lesson, you will work in the Python Editor, investigate the menus, use some mathematics operations, experience color highlighting, note some special keypad changes and work with different data types.
- Explore the menus
- Use some operators
- Learn about several of the basic types of variables
- Use the assignment statement (=)
- Experience the keyboard differences in the Editor
Start the Python App from the [prgm] key. You see the Python FILE MANAGER. The image shown here illustrates what happens as you write more programs. GRAPH, HELLO and LINREGR are in the list but there are lots of other files, too. Your screen will surely resemble this someday. #coding goals
If you are already using the Python App, select <Files>.
Select <New> on the menu bar to begin a new Python program. Before entering the Editor, you must provide a name for this file. It must conform to the rules posted on the screen. The cursor indicates that you are now in uppercase alpha mode for entering the name of the program. At the end of the filename press [enter] or select [Ok]. We will name the new program FIRST, but you can use any valid name.
Note: It must be all uppercase because the TI-84 Plus CE Python requires it for all identifiers and variables. The program is stored as an AppVar.
y = 3*X + 7
z = 5*X - 2*y
print(X, y, z)
Press [X,T,θ,n] for the Capital X.
Press [alpha] then the appropriate key for the other letters.
Use the [sto ->] key for “=.”
Comma (,) is above the “7” key on the keypad.
You must use a multiplication sign: 3x causes an error.
To type print, turn on alpha-lock ([2nd ] [alpha]) and turn it off when done.
Notice that none of these statements produce any output yet. You are just editing a program.
Uppercase X is produced by pressing [X,T,θ,n]. For lowercase x use [alpha] [sto ->] or [alpha] [X,T,θ,n]. You can use either uppercase X or lowercase x but you must be consistent in your program because Python is case sensitive. X and x are different variables.
About editing. The cursor is always in “insert” mode. [del] deletes the character to the left of the cursor (backspace). Pressing [enter] at any time forces a new line. The [clear] key erases the entire line and on <Tools> the
Pressing [alpha] switches among numeric, lowercase and uppercase. [2nd] [alpha] turns on/off alpha-lock. While in alpha-lock you can use [alpha] to switch between lowercase and uppercase. Press [2nd] [alpha] again to turn alpha-lock off. Pay attention to the cursor symbol and the status line at the top of the screenAn alternative to the keypad is the on-screen text selector: Selecting the <a A #> menu opens the text-selection window (see image). Use the arrow keys and press [enter] or select <Select> to build your text at the top of the screen. Select <Paste> to add it to your code at the current cursor position.
- The equals sign (=) is the assignment operator; it stores the result of the expression on the right to the variable on the left
- An expression is a combination of numbers, variables and operators such as 5*x-2*y that is evaluated to produce a result
- Syntax is the grammatical structure of a language; the order of the pieces of a statement matters
9 34 -23
indicates that, as a result of the previous statements, x is 9, y is 34, and z is -23. The other statements do their work behind the scenes.
Note: Improving the output of a program is one of the most engaging parts of programming.
Errors. Programming errors come in three flavors:
- Interpreter errors are usually reported as a “SyntaxError” (or similar) before execution begins
- Runtime errors are detected by the computer during execution (like “division by zero” as seen in the image which was caused by the statement X=3/0
- The third kind of error is in the head of the programmer, for example, entering a valid, but incorrect expression (like misuse of order of operations) or logical structure (like using “and” where “or” is required); example: 5+3/7+1 vs. (5+3)/(7+1) (order of operations); both are evaluated properly but give different results; what did the programmer intend?
Return to the <Editor> containing the three expressions and the print( ) statement. To improve the appearance of the output, add a “message” (such as “x=”) to each of the values:
print("x=",x," y=",y," z=",z)
There are some spaces in front of y= and z= inside the quotes. Spaces are ignored by the interpreter, but if they are inside the quotes they will be printed as written.
Be very careful when entering this statement: The positions of the commas and the quotes is crucial. If any symbol is in the wrong position, you will see a “SyntaxError” message when you select <Run>. You will have to find and correct the error, which is usually near or right above the cursor.
Skill Builder 3: Introducing the Python FunctionDownload Teacher/Student Docs
In this lesson, you will define a function and use the function to evaluate expressions. You will experience the purpose of indentation in Python Editor.
- Define a function
- Use the function in evaluating expressions
- Use the input() function
Functions play a big role in Python programming as in mathematics. Functions can be used to generate many different kinds of values, and functions can serve as Python subroutines which help to break a complex process into smaller, manageable parts.
A program is a step-by-step recipe for solving a problem: an algorithm. All programs are algorithms underneath.Write a program that lets the user enter a number for x, and the program will use that value to evaluate the function f(x)=x2 + 3x - 1. Start a new blank Python program. Ours is simply called “A.”
Define a function: Select <Fns…> def function(). The function template appears in the Editor. You must supply the name of the function, the argument(s) for the function and the code for the function block.
The name of the function goes to the left of the parentheses. Leave a space after the keyword def.
The argument(s) of the function go inside the parentheses. If there is more than one, use commas to separate them. There may also be no arguments.
The image shows the function defined as:
Important tip: The colon (:) at the end of the line indicates that the next section is the function block and the next line is indented two spaces. Indentation is critical in Python programs. This is how Python interprets function, loop, and If blocks. This Editor uses light gray diamond symbols (♦ ♦) to help with proper indentation.
Type the expression:
return x**2 + 3*x - 1
remember to use the [ ^ ] key for ** (the “raise to power” operation) and remember to use the multiplication sign in 3*x. 3x is an error.
We have finished defining the function. When you run this program, this function definition is not executed right away but the Shell “knows” that it exists.
Now write a “main program”:
Statements that allow the user to enter a number and produce (print) the function’s value for that number.
Press [enter] and [del] the indent spaces on your new line.
Create the statement:
x = input(“Enter a value for x: “)
Begin by typing the letter x and use [sto] for the “equals” sign. Select <Fns…> and then right-arrow to the I/O menu (across the top line of the screen).
For the text in quotes, turn on alpha-lock and use the keypad to type your text. The quotation mark (“) is on the [+] key. [space] is on the  key, and the colon (:) is on the [.] (decimal) key.
Press [enter] after the closing parenthesis and, on the new line, write the statement:
print(“f(x) = “, f(x))
Recall that print( ) is on <Fns…> I/O.
The text gets tricky because you have to turn alpha-lock off to type the parentheses and = sign inside the quotes. Another option is to use the on-screen text selector found by selecting the menu <a A #>.
Note: Your print( ) statement actually contains f(x) twice: one in quotes (green) and one at the end (black). Both are typed by you, but the first one (green) is displayed as is. The second one, f(x) , calls the function at the top of your code and processes the function’s expression to be displayed here.
Welcome to (possibly) your first “runtime” error. The message is lengthy but the important part is in the last two lines. Note the last line number and the TypeError: “can’t convert…”.
The error happens because the input() function returns a string, not a numeric value. The programmer (that’s you!) must convert the string to a numeric value.There are five simple types of data in Python: int (integer), str (string), float (numbers with decimals), complex (complex numbers) and bool (Booleans are either True or False).
Note: True and False are the only Python keywords that are Capitalized
They are int(), float(), str() and complex().
Try both and see the difference.We chose float() in this example. Why?
<Run> the program again, and it will (should!) work as intended. Be sure to test your program with numbers for which you can confirm the calculation yourself!
Note: If it does not work, check your code! That’s “debugging.”
Application: Two Functions Are Better Than OneDownload Teacher/Student Docs
In this Application, you will make a second function and use both functions to investigate some of the mathematical properties of functions.
- Editing a Python file
- Copying a Python file
- Adding a function
- Evaluating function expressions in the Shell
- Creating an inverse function.
In the last lesson (Unit 1, Skill Builder 3) you defined a function f(x). In this application you will add another function to that file and then evaluate some expressions using those functions.
Making a copy of a program. Either start the Python App by pressing [prgm] or in the Python App go to the File Manager (select [Files] from either the Editor or the Shell).
Point to your Skill Builder 3 program in the list and select [Manage].
Choose Replicate Program…
Enter a name for the new program. The new program is loaded into the Editor for you to revise.
Now add a second function template below the function f(x):
On a blank line, press menu > Built-ins > Functions and select def function().
Again, the syntax for the function structure includes a colon (:) at the end of the def line. This indicates that the following code is the definition of the function and the block is indented two spaces.
Complete the def statement by naming the function g and using the argument x.
Using the [del], revise f(x) by removing the x**2 term:f(x) = 3*x - 1
return -2*x - 4
Turn each of the last three lines of code in the program into #comments:
Place the cursor at the start of the line.
Select [a A #]
Press [enter] on the # character.
just press [2nd ]  for the # character
Note: Only the first line of code is commented in this image. Comments are grey. The # character indicates that the rest of the line is a comment and is ignored when the program is run.
After all three lines are comments [Run] the program, the Shell appears, but nothing else happens because only the two functions are defined. Press the [vars] key and you will see the two functions listed. You can select one by pressing [enter].
Complete the expression>>> f(1) + g(1)
by either typing it or by selecting f() and g() from the [vars] menu.
Press [enter] to see the result.
Try other expressions using both functions like:
f(4)+g(1) f(5)+g(2) (f+g)(4) f(g(6))
Composition and inverse functions
Are you ready for this? Back in the Editor, change g(x) so that f(g(x)) = g(f(x)) ALWAYS (regardless of the value of x). Test your functions carefully in the Shell by selecting <Run>:
>>>> f( g(4) )
>>> g( f(4) )
Hint: Both of these expressions should produce 4 and using any other value in place of 4 should produce the value that you use.
- Skill Builder 1
- Skill Builder 2
- Skill Builder 3
Unit 2: Input, Output and Functions
Skill Builder 1: A Tale of Two MeansDownload Teacher/Student Docs
In this lesson, you will write a program that requires a mathematical function that is not part of Python’s ‘built-in’ tools.
- Use import for additional functions
- Write a program using the menus
- Examine a mathematical relationship
|The arithmetic mean (average, pronounced ‘arithMETIC’)|
|of two numbers is:|
|The geometric mean is:|
Write a program to calculate and display both means to compare them for several examples.
Begin a new Python program and name it TWOMEANS.
Start a line with the # sign (‘pound’, ‘number’, or ‘hashtag’) found on
<a A #>. Highlight the symbol, press [enter] and select <Paste>. This symbol is used for making a #comment which is ignored when the program runs. After the # sign write a sentence explaining the purpose of the program. Comments are useful in two ways:
- They allow the programmer to document the purpose for different chunks of code. This makes longer programs easier to read and debug if there are errors.
- They are useful in debugging because you can ‘comment out’ a line so it does not execute when the code runs. That allows the programmer to systematically isolate where the error occurs.
Note the wraparound feature in the Editor: the remaining part of the line is also indented a bit.
This program requires the square root function which is not part of Python’s built-in operations. Square root (sqrt) and other mathematics functions are found in the standard Python module called math. To use this function, you must ‘import’ the math module to your code. Select <Fns> Modul > math and select the statement at the top:
from math import *
Modules are used to keep Python small and fast: We only import stuff that our program will actually use.
The Math menu contains lots of mathematics functions and there are separate Const and Trig sub-menus, too. To use any of these functions the math module must be imported into your program.Note: the asterisk ( * ) means ‘ from math import all’
Use the input( ) function to enter the first number. First type the variable a and the = sign ([sto] key).
Recall that input( ) returns a string and we must convert it to a number. Combine those two steps into one by writing:
a = float(input( ))
First, get float() from <Fns…> Type,
Then, with the cursor inside the parentheses, look on <Fns…> I/O for the input( ) function.
For the prompt inside the input( ) parentheses, write “First number?”
The question mark is on the <a A # > screen.Write a second statement to enter the second number (not shown). This is a good opportunity for you use the <Tools> Copy Line and Paste Line Below features and then edit the second line.
After your two input statements, write two assignment statements, one for the arithmetic mean and one for the geometric mean:
am = (a + b) / 2
gm = sqrt(a * b)
sqrt() is on <Fns…> Modul > math.
You can also simply type sqrt( )
The last task is to write the print() statements to display the two calculated values. Use your imagination! A sample is shown here:
print( "am = ", am)
print( "gm = ", gm)
Run the program and enter two numbers for which you know the answers…TEST, TEST, TEST.
To rerun the last program, select <tools> and press [enter].
After trying many examples, do you notice a relationship between the two means? Is one always larger than the other? Are they ever equal? How are they related to the two numbers you enter? Are there any values which cause an error?
Check your guesses with the teacher! Can you prove it?
Skill Builder 2: Heron’s FormulaDownload Teacher/Student Docs
In this lesson, you will use one of the program templates, create a function to evaluate and return a value, and explore the mathematical operators.
- Use a program template (Type:)
- Create a function for Heron’s Formula
You are given a triangle with only the side measurements. Can you determine the area? YES, using Heron’s Formula.
In this lesson you will create a function to determine the area of a triangle using the three side lengths and then complete the program that uses that function.
This program, like the last one, requires the sqrt() function. This time we will use one of the included Python “templates” which preloads the most commonly needed functions for the project.
Go to the FILE MANAGER (either start Python on the [prgm] key or select <Files> within the app).
When you are entering the name of a <New> program in the FILE MANAGER and are entering the name of the Python file (we use “AREA” for this filename) there is a <Type> menu on the bottom of the screen. Select <Type> and see a list of the types of programming templates that are available. The default type is “Blank Program.”Select the Math Calculations program type.
The filename entry screen now shows the template selected:
at the bottom.
Press [enter] to start the Program Editor. Notice the comment at the top indicating the type of project you are making: #Math Calculations. The import statement has been provided for you.
Now insert the def function() statement by selecting <Fns…> [enter].
Make the name of the function heron. There are three arguments, a, b and c, which represent the three sides of the triangle.
Be sure to leave the colon (: ) at the end of this line!
See the next step for the code for the block.
Heron’s Formula is a two-step calculation:
First, calculate half the perimeter (the semi-perimeter):
♦ ♦s = (a + b + c) / 2
Then the area is:
♦ ♦area = sqrt(s*(s - a)*(s - b)*(s - c))Remember that both statements in this function block are indented. The two diamond (♦ ♦) spaces are provided for you on each line.
Finish the function by providing the return statement:
♦ ♦return area
found on <Fns…>. You must type the variable name area.
Now it’s time to write the main program using just the statements:
input() (3 times for the three sides)
print() (to print the area)
Before going to the next step, try writing them yourself.
Start with the cursor at the beginning of a line (delete any indentation spaces).
The three input() statements request the lengths of the three sides, convert each length to a number, and store the values in three variables. We use x, y and z.
x = float(input(“enter first side: “))
The other two are similar, so take advantage of copy/paste on the <Tools> menu.
The print( ) statement prints the value of the heron function using the three variables as arguments:
print(“area = “ , heron(x, y, z) )
Note that these last four statements are not indented.
Test your program with numbers for which you know the area, like 3, 4 and 5. Why is the area 6? What other triangles have areas that are easy to compute when given the three sides?
See the next step if you get an error message.
If you get an error message when you run the program, read the message carefully, paying attention to the line numbers mentioned and the type of the error. For example: The NameError to the right occurred because the code contained a capital Y in one place and a lowercase y in another place.
Skill Builder 3: The Midpoint FormulaDownload Teacher/Student Docs
In this lesson, you will write and use a function that is used more than once.
- Review the midpoint formula
- Use uppercase in a variable
- Store the result of a function in a variable
- Return two values from a function
In coordinate geometry there is a method for determining the coordinates of the midpoint of a line segment given the coordinates of the endpoints. Write a program that determines the midpoint’s coordinates.
There are two midpoint formulas that are really the same formula (the arithMETIC mean of two numbers) using different variables:
midX = (x1 + x2) / 2
midY = (y1 + y2) / 2
In a new Python file (our file is named MIDPOINT), select <Fns…> and use the def function( ): template.
Name the function midpt( ).
This time write the main program first, then come back to code the midpt( ) function last. Place your cursor at the beginning of a blank line below the function name. Write the four input statements to enter the four coordinates of the endpoints using x1, y1, x2, y2 as the four variables. Try it before moving to the next step.
Remember to take advantage of copy/paste. You can copy once, then paste three times.
The image on the right shows all four input statements. The first is:
x1 = float(input(“x1 = “))
Copy and paste comes in handy here. With your cursor on the x1= line, select <Tools> Copy Line and then select <Tools> Paste Line Below three times. Then be sure to edit the pasted code to suit.
Write two assignment statements to store the result of the midpt( ) function into two different variables:
midX = midpt(x1, x2)
midY = midpt(y1, y2)
(We are using the same function for two different sets of variables.)
Write the print statement to display the complete midpoint:
print(‘midpoint =‘, )
Can you complete this statement so that the output appears as an ordered pair? For example: midpoint = (13, 5)
Now go back to complete the midpt() function.
Use two arguments. It is better to use two new variables as arguments:
Try completing the function now. Then compare your work to the next step.
The body of the function consists of one calculation:
♦ ♦avg = (a + b) / 2
and the return statement:
♦ ♦return avg
We use the variable avg because the expression is calculating the average or arithmetic mean of the two arguments.
Make sure that these two statements are indented the same amount.
Recall that return is found on <Fns…>.
If you have completed the print statement, then run the program and enter four values at the prompts. Does your output resemble ours?
Summary: Python functions can be used many times during a program.
Displaying output in a pleasing format can be tricky. Our print statement is:print( “midpoint = ( “, midX, “, “, midY, “)” )
with extra spacing to see where the quotes and commas belong.
Why are there decimals in the output? because we used float( ) in the input statements.
Application: Distance to the HorizonDownload Teacher/Student Docs
In this Application, you will write a program that determines the distance to the horizon from a given altitude.
- Use import for additional functions
- Write a program using the menus
- Use multiple units in one problem
When a plane is flying, how far away is the horizon to the pilot? The higher they fly, the further the distance to the horizon. How do they determine the distance to the horizon given the plane’s altitude?
The radius of the Earth is 3,958.8 miles.
Write a program to input the altitude of the plane in feet and produce the distance to the horizon in miles.
Start a new Python file (we call it horizon).
Start with a comment explaining the purpose of the program. You can press [2nd ]  for the # symbol and turn on alpha-lock for the rest of the text. Remember that the space is on the [ 0 ] key.
This program uses the Pythagorean Theorem and requires the square root function which is not part of Python’s built-in operations. This function, and others, are found in a standard Python module called math. To use this function, you must import the math module to your code. On menu > math, select the statement at the top:
from math import *
Recall that the asterisk (*) means “everything.”
Use the input() function to enter the altitude of the plane.
First type the variable alt and the [sto ->] to get the = sign.
Then look on <Fns…> I/O for the input() function.
For the prompt inside the parentheses, write: “altitude (ft)?“Tip: Remember many symbols including ? can be used from the <a A #>.
Remember that input() gives a string that must be converted to a number. On the next line, convert the string alt to a float (decimal) value:
alt = float(alt)
float() is on <Fns…> Type.
From our labeled diagram we see a right triangle where one leg is the radius of the Earth, the other leg is the distance from the plane to the horizon and the hypotenuse (the radius of earth plus the altitude of the plane). The Pythagorean Theorem states that, in a right triangle:
|(leg1)2 + (leg2)2 = hyp2|
|or||radius2 + leg22 = (radius+alt)2|
So, solving for leg2 gives: leg2 = sqrt((radius+alt)2 – radius2)
The Python exponent symbol is **
Enter this formula into your program:
leg2 = sqrt((radius + alt)**2 – radius**2)
Yes, you may use shorter variable names!
Be careful with the parentheses.
Pressing the [ x2 ] key produces **2 in your code.
Pressing the caret key [ ^ ] produces **
Or you can just type them yourself.
There are two more details to handle before we can test the program.
- Set the variable radius to be 3958.8:
radius = 3958.8
- Convert the altitude variable from feet to miles:
alt = alt/5280
Both of these statements must occur before the Pythagorean Theorem formula, as shown here. If you made a mistake, under <tools> try cut and paste the line to the new location.
You are almost ready … you still must print the answer.
gives the answer, but a more informative message would be:
print( “ Distance to horizon: “ , leg2 , “ miles. “ )
When ready, select <Run> to run the program. Try various altitudes.
If you see a SyntaxError, check your punctuation carefully.
Extra spaces have been added to illustrate order of the punctuation.
Challenge: Revise the program to use a defined function to calculate the distance. There will be one argument for the function: the altitude (n feet). The function returns the distance (in miles).
Find the altitude of the outdoor observation deck (86th floor) of the Empire State Building in NYC. Use this program to determine how far you can see in any direction. Or you can use the NYC One World Trade Center observation floor, or the highest one in the world, the Burj Khalifa observation deck in Dubai.Can you write a metric version?
- Skill Builder 1
- Skill Builder 2
- Skill Builder 3
Unit 3: Conditions, if and while
Skill Builder 1: CollatzDownload Teacher/Student Docs
In this lesson, you will ‘branch’ out into the world of conditional programming. You will also investigate a mathematical theory that is (so far) unproven.
- Learn the relational and logical operators
- Learn the integer operators (% and //)
- Write programs using if statements and while loops
Choices, choices, choices. Our life is one long series of decisions: Are you hungry? What to eat? Is it cold? What to wear? Are we there yet? This decision-making process in programming is handled with if statements and while loops, which both depend on conditions. Examples of if and while in action are seen in in this image.
A condition is an expression that results in the value True or False:
X > Y A+B <= C Qty > 0 5 != 3
are all examples of conditions. (does not equal)
A condition includes one or more of these relational operators:
== > < != >= <=
Caution: Remember to use == when writing a condition, not =. Using the wrong symbol will result in a syntax error. Write if x==5:, not if x=5:. Using the [test] menu can help.
This lesson introduces you to these powerful programming tools.
The Collatz Conjecture Begin with a blank Python file (we called it COLLATZ). int( is found on <Fns…> Type.
Algorithm: Take a positive integer, if it is even, divide it by 2,
otherwise multiply it by 3 and add 1.
Repeat with the result.
What happens to the sequence?
Input an integer to the variable num using the statement:
num = int( input( "Enter a positive integer: "))
Begin with a blank Python file (we called it COLLATZ).
int( is found on <Fns…> Type.input( is found on <Fns…> I/O.
if statements come in three flavors: if.., if..else.., and if..elif..else... They are all found on <Fns…> Ctl. Note that there is no ‘then’ in Python.
(They are on the Ctl menu because these statements Control the flow of your program.)If..Use when there is no ‘otherwise’ action. If..else..Use when there are exactly two alternative actions
for Trueand False.
(We will use this one soon.) if..elif..else..Use these when there are three or more actions to be taken based on several conditions.
elif is short for ‘else if…’ and requires a condition just like if.
You can add as many elifs as your algorithm requires.
(This structure is used in the application for this unit.)
There must be a colon ( : ) at the end of each if, elif and else . These colons are required and indicate that what follows are the actions to be taken when the condition is True or False.
Insert the if.. else statement from <Fns…> Ctl.
The condition (written between if and the colon) is …
if num % 2 == 0:
% is called “mod” and is the mathematical operator (like +, - *, and /) that gives the remainder when the first number is divided by the second. “mod” is short for “modulus.”
% is found on the <a A #> screen or in the catalog [2nd] .
The statement now reads: “If the remainder when num is divided by 2 is zero,” which means “if num is even…”
Note the two equal signs!
For == just use any of the following:
- press the [sto ->] key twice or
- select it from <Fns…> Ops or
- select from <a A #> or
- press [test]
if (the number is even) :
♦ ♦(the “True” block)
♦ ♦num = num // 2
Just use two / signs (the [ ÷ ] key).
// (two division signs) is called floor division (no decimal and truncates to the integer just below the decimal value). If you use / you will see a decimal point even if all the numbers are integers.
else: (when the number is odd — no condition here) :
(the “False” block)
♦ ♦num = 3 * num + 1
After the if.. else: structure, backspace to the beginning of a line (erase the indent characters) and write the print statement:
Running the program:
Select <Run> to run the program. Enter a positive integer. An answer appears. Remember it!
Select <Tools> [enter] to run the program again and this time enter the last answer.
Repeat running the program, each time entering the previous answer.
But wait! Let’s add a loop to the program so that the process runs repeatedly by itself instead of having to run the program over and over.
Place your cursor right below the input statement and above the If statement as shown in this image.
On this blank line add the while statement found on
You will see:
pasted into your program and your cursor is blinking on the colon.
Indent each line below while: (the if.. else structure and the print statement) by:
- Place your cursor anywhere on a line
- Select <Tools> Indent►
Blank lines and #comments do not need to be indented since Python ignores both.Indenting causes the statements to become the block of code inside the while structure. You still need to write the while condition.
Now write the condition after the word while (leave a space after while and do not erase the colon).
The Collatz Conjecture states that all sequences will eventually become 1. As long as the number is greater than 1, continue processing so write:
while num > 1 :
Run the program now. Enter 20 as the number. Follow the logic of the program. Odd numbers get larger and even numbers get smaller:
20 is even → 10
10 is even → 5
5 is odd → 16
16 is even → 8
and so on …
… and the program ends when the number reaches 1.
Note that it only took one line of code to create a loop!
Can you find a number that causes the program to NEVER end? Try a large number. Notice how fast the numbers fly by! When the program ends you can scroll upward through the Shell history ([2nd] [uparrow]) to examine the numbers.
Skill Builder 2: Flag WavingDownload Teacher/Student Docs
In this lesson, you will learn about counters and accumulators by calculating the number and the total of numbers entered and determine the average of the numbers.
- Counter statement
- Accumulator statement
- While loop with a flag
- Calculating an average (mean)
You will write a program that will count and add up a set of numbers. You do not know in advance how many numbers there will be. This lesson introduces the concept of a counter statement, an accumulator statement, a ‘flag’ value to end a loop, and the calculation of the average of the entered numbers.
Begin a new Python file and name it COUNTER.
Make two variables and set them both equal to zero:
count = 0
total = 0
count keeps track of how many numbers are entered and
total keeps a running total of the numbers that have been entered.
A third variable, num, stores each number entered one at a time.
Rather than setting it equal to 0, use an input statement to get the first number from the user:
num=float(input(“Enter a number: ”))
Remember that most of the Python programming tools are found under <Fns…>.
Now start a while loop that will end when a certain number is entered. Some options here are 0, -999 or -1. Keep in mind that this unique number cannot be one of the numbers you are trying to process. We will use -999 as our “flag” value to signal that we have finished entering numbers.
while num != -999:
Recall that while is found on <Fns…> Ctl and != is on all the places you can find ==. Simplest is the [test] menu.
The while loop block will:
- Count the number of numbers entered.
- Add them up.
- Then, ask for another number.
count = count + 1
which adds 1 to the variable count each time it is processed.
Adding them up, or totaling, is accomplished with the statement:
total = total + num
“Ask for another number” requires an input statement like the first one:
num=float(input(“Enter a number (-999 to end): ”))
but here we add a message telling the user how to end the loop.
Tip: Copy the first input statement and paste it here, then edit it. Be sure all three of these statements are properly indented.
The input statement comes last in the loop body to control the loop.
Question: Is -999 included in the total?
Tip: If your program does not end when you enter -999, you can press [on] to break it, go into the Editor and check your code.
We have finished with the loop. Skip a line or two and erase (backspace) the indent spaces. Note the cursor position in this image.
Now is the time to process the inputted numbers. We kept track of the count and the total so now (after the loop ends) we can calculate the average.
Try it yourself before looking at the next step.
avg = total / count
calculates the average and stores the result in the variable avg.
Ponder this: Why do we use / here and not // as in the last lesson?Finally, write the print statement(s) that report the count, total and average to the user. You may wish to use more than one print statement. Our code is shown in the next step.
We use three print statements to report the results:
print(" Count = ", count)
print(" Total = ",total)
print(" Average = ",avg)
Skill Builder 3: Press a keyDownload Teacher/Student Docs
In this lesson, you will use a function that looks for a keypress to terminate a loop. This feature is unique to the TI-84 Plus CE Python graphing calculator, so you will need to import one (or more) special modules.
- Use get_key() to end a loop
- Examine powers of 2 and powers of 1/2.
- Use sleep(n) to pause code execution for n seconds
Begin a new Python blank program and name it “POWERS2.”
Select <Fns…> Modul ti_system to get the statement
from ti_system import *
located at the top of the list.
From the same menu, select the special statement:
while not escape():
The [clear] key will terminate this loop.
Now introduce a variable num = 2 just before the while statement.
In the loop block (below the while statement and indented two spaces), print the variable num and then make an assignment statement that multiplies it by 2. Be sure both statements are indented.
Try it yourself before checking the code in the next step.
Here you go:
while not escape():
♦ ♦ print(num)
♦ ♦ num = 2 * num
Again, watch the indentation carefully!
Run the program and press the [clear] key to stop the loop.
[clear] is used as the (missing) [esc] key.
The numbers grow really fast!Two interesting features of Python:
- It’s really fast, and
- There’s no upper limit to the integers
However, you are limited by the capacity of the computer’s memory.
Your next task is to slow things down so that you can read the numbers.
You need a function called sleep() that is found in the Python time module.
At the top of your program add the statement
from time import *
located on the top of <Fns…> Modul time.
inside the while block (indented like the other two statements above it).
Run the program again. This time, after each number is displayed, the computer sleeps (waits) for one second before proceeding to the next step in the loop. Change the sleep number to speed things up a bit. Again, press [clear] to end the program. Try other sleep() values to vary the speed of the display (yes, you can use decimals).
At the end of the program, print(“done”).
Running the program with sleep( ) in the loop causes the numbers to appear at a slower rate.
Displaying “done” at the conclusion lets the user know that the computer is now ready to do something else.
Extra: Change each 2 in the program to 0.5.
Try other numbers.
When do the numbers grow and when do they shrink?
How about using negative numbers?
Would it make sense to try 0 or 1 instead of 2?
Now try this: Change num = num * 2 to num *= 2
This shortcut operation does the same thing and works for many other mathematical operators.
Application: FizzBuzzDownload Teacher/Student Docs
In this Application, you will write a program to illustrate the amazing ‘FizzBuzz’ phenomenon.
- Make a while loop that terminates in two ways
- Define a function that examines numbers for ‘divisibility’
Other requirements: The program should end when the esc key is pressed.
‘Divisibility’ is tested using the % operator (mod or remainder).
There is one other form of the if statement you will find useful:if <condition>:
elif <condition2>: there can be many elif blocks
<true block2>   elif is short for ‘else if’
<false block> this block is processed when none of the
others are true.
Begin a new Python blank program file. We named it FIZZBUZZ.
#: It always helps to write a comment at the top of the code explaining the program. You may want to add your name and date here, too.
from ti_system import *
while not escape():
which are both found on <Fns…> Modul> ti_system.
Before the while loop, set up a variable that represents the counting numbers starting with 1.
Use the if..elif..else structure found on <fns…> Ctl.
Remember that it works like this:
if <this is true>:
(there may be more elifs in here)
<do this> (when none of the others are true)
Caution: Remember to use == when writing a condition, not =. Using the wrong symbol will result in a syntax error: if x==5: not if x=5:Using the [test] or <Fns…> Ops menu can help.
Here is a peek at the if .. elif .. else structure, but some information has been omitted, so that you can try to write the code on your own.
The if and each elif has a condition to be met and a code block to be processed when the condition is true. else: has no condition and its block will be processed when none of the others are true.
counter+=1 is shorthand for counter = counter + 1.
Hint: Recall that A % B gives the remainder when A is divided by B.so, for example, if counter % 5 == 0 then the counter is divisible by 5 and “Buzz” will be printed.
The conditions and the print( statements in the image are incomplete.
A run of the program should look something like the image to the right.
If your numbers go by too fast, use a sleep() function in the loop to slow things down a bit.
sleep() is in the time module so be sure to include:
from time import *
What is the first number replaced by “fizzbuzz”?
- Skill Builder 1
- Skill Builder 2
- Skill Builder 3
Unit 4: for loops and lists
Skill Builder 1: Home on the range()Download Teacher/Student Docs
In this lesson, you will create your first of many for loops and examine the many advantages of iterations.
- Explore the range() function
- Use in to test for membership
- Write a for loop
Python’s built-in range() function is used to generate an arithmetic sequence of integers. In this lesson you will use the range() function to make a for loop.
First, do some code testing using the Python Shell to see what the range() function does in a for statement. The Shell is a good place to test code out without writing a program. You can switch to the shell at any time to try something out.
From the FILE MANAGER, go to <Files> and select <Shell>.
At the Shell prompt, add the command found on <Fns…> Ctl:
>>> for i in range(5):
Press [enter] and you will see three dots. Python “knows” that you are entering a code block so the cursor is indented.
Enter the print(i) function from <Fns…> I/O and you must also type the variable i inside the parentheses.
Press [enter] twice to tell Python that there are no more statements for this block. The Shell will then process the command block and display the range of numbers 0, 1, 2, 3, 4.
There are other possible formats for the range() arguments on the Ctl menu shown in this image:
- start is the starting number
- size, stop or stp is the number that ends the loop but it is not processed
- step is the increment (step) that is added to the loop variable in each iteration of the loop.
- All three arguments must be integers
Write a program (LOOP1) that prints a range of numbers using a for statement. Start a new Python file and add the simplest for statement:
for i in range( ___ )
located in <Fns…> Ctl.
You can change the loop variable i to any variable that is more appropriate for your program. Inside the range parentheses, type an integer greater than zero. We will use 5.
In the loop body add the print statement:
♦ ♦ print(i)
Remember that this statement is indented to be the body of the loop.
Notice that we used 5 for the range() argument.
Run the program. Without a start value, the first value printed is 0 and the last value printed is one less than your range argument. There are 5 numbers printed in this image. If you used a large* range argument you will see that many numbers printed, just not the last one. Go Back to <Editor> and enter another number to see.
Without a step value, the increment is 1.
Programmers always start counting with 0.
Tip: Again, to “break” (stop) a running program, press the [on] key on the keypad until you see the KeyboardInterrupt message.
*Not too large: It could take a while.
There are two other for loop options that use range() found on the Ctl menu. The image to the right shows each in a sample program but they are incomplete.
Use the third format to make a “countdown” loop that goes from 10 to 0 by 1s. Try it now, and then go to the next step.
When you run the program, did it look something like this?
This loop stops at 1 (still 1 short of the stop value) because the program is
for i in range(10,0,-1):
which stops at 1, not 0.
Again, the stop value of a loop is not included in the loop body (block).
To include 0 in the output make the loop use:
(10, -1, -1)
Write a new program (SQUARE) that prints the squares of numbers between (and including) two entered numbers by using input().
In a new file, write the two statements to input a lower and upper bound of the range (not shown).
Next, write the for loop using the (start, stop) template.
Notice that the upper bound is upper + 1 to ensure that upper is included in the printout.
The loop block should just print the number and its square (not shown).
Compare your program to the one shown in the next step.
Use int(input()) to convert the inputted string value to an integer.
Using float() would cause an error in the range function.
The print statement prints both i and i*i separated by a comma.
You could also use i**2 to square a number.
Run the program: First enter values for lower and upper. Then, the program prints the squares starting with lower and ending with upper. If you enter a larger range of values the Shell will scroll to continue printing.
Tip: To scroll up through the Shell history (backwards, going up the screen) press [2nd] [uparrow].
Try entering various ranges and determine the behavior of this loop. Can you use negative numbers? What happens if upper is smaller than lower?
Skill Builder 2: Welcome to ListsDownload Teacher/Student Docs
This lesson introduces you to Python lists, which are similar to, but not the same as, TI-84 Plus CE graphing calculator lists.
- Create a list in the Shell
- Write a program to make a list
- List functions: .append()
- Add elements to a list
- List tools on the menu
- Analyze a list: mean
Our first venture into the world of lists takes place in a short program to make and display a list.
In a new program, see <Fns…> List for the major list functions shown in the image, like the square brackets [ ], list(), .append() and others.
The assignment statement
a = list(range(5, 10) )
stores the numbers from 5 to 9 into the variable a as a list.
range( ) provides the numbers and list( ) arranges them into a list.
Find list( ) on <Fns…> Lists.
Find range( ) by pressing [2nd] [ 0 ] to access the catalog and press the [R] key to jump to the “R” section of the catalog.
The assignment statement only stores the list in the variable. To see the contents of the list use print(a).
Run the program to see the result.
To refer to an element use the syntax a (square brackets) to see the fourth element, 8, as shown in the Shell. The square brackets, [ ], are on the keypad ([2nd] [x] and [2nd ] [-]) and on the <a A # screen> and on <Fns…> Lists.
The elements of the list are accessible by their index, but the first element of the list has index 0.
The list a has 5 elements, 5, 6, 7, 8, 9, and the indices are 0, 1, 2, 3 and 4. There is no element a in a 5-element list.
List a looks like this:
The elements can be any Python data type, including lists themselves.
Both the index and the element can both be represented by variables as you will see next.
Write a program that makes use of a list of numbers that we will enter using input. But first, we will tell the program how many numbers there will be.
In a new Python file, use an input() statement to enter the number of numbers (we used the variable amt).
Create an empty list using the assignment statement:
nums = [ ]
This list will be used to store all the numbers entered.
You can easily type the two square brackets using [2nd] [x] and [2nd] [-] or select them from <Fns…> Lists or from the <a A #> screen.
Tip: If you use a plural like nums for a list name, it helps you remember that it contains many values.
Add a for loop to enter the numbers.
Use the loop index i. The range value is amt, the variable that holds the number of numbers to enter.See the next step for the for block.
print the index value i. This represents the index of the list or the “Element number.”
Then write an input statement to enter the number. Use a float() function to allow a decimal value:
value = float(input(“enter value: “))
float() can be found under <Fns…> Type.
To add each value to the list nums, use the Python function:
Type the list variable nums, then get .append() on <Fns…> Lists.
Use the variable value as the item to append to the list.This is the last statement of the loop block. Press backspace (del) to the beginning of the next line to write the summary code.
Print the list with the single statement:
This would be a good time to test your program. When you run the program, enter the number of numbers you plan to enter and then enter each value one at a time. The print statement tells you which element you are entering, but remember that the count starts with 0.
After entering the numbers, you should see the list displayed in square brackets like this: [45, 43, 89, 25]. (Your numbers will be different.)
There are many useful list functions in Python.
See <Fns…> Lists again.
Scroll all the way down.
Note: Some of these functions begin with a period (.) and others do not. A dotted function must be preceded by a list name like nums.append(). Undotted functions take a list name as an argument such as min(nums).
Get the sum() function from the <Fns…> Lists menu. To calculate the arithmetic mean of the list, use the formula:
mean = sum(nums) / amt
Add a print( ) statement to display the mean.
What additional summary information can you display?
Is there a “geometric mean” as well?
Skill Builder 3: Throwing in Some RandomnessDownload Teacher/Student Docs
In this lesson, you will make a list of random numbers to investigate patterns.
- Use randint(a,b)
- Create a list of random integers
- Analyze properties of the list
Lists (or arrays) are a convenient way to store many different values in a single variable. Python is very flexible with the contents of a list (it can hold different types of values, but this is rare) and has several ways of making a list.
One expression worth noting is 3 *  which “replicates” the element three times.
What does 3 * [1,2,3] produce? The same expression in the calculator app gives a completely different result as shown in the second image.
Use caution when working with lists in Python because the result might not be what you expect.
We will stick with the basics in this lesson which makes a list of random numbers and then calculates some “1-Var Statistics” on the data.
For this project, when creating the <New> Python program, when entering the program name, choose Random Simulation from the <Type> menu.
Our program is named RANDOM1 and the template provides a comment and the statement:
from random import *
Do not select anything yet, but look at the contents of the random module:
Select <Fns…> Modul > random… to see that it contains several functions that generate “random” values. randint(min, max) generates a single random number between min and max, values that the programmer provides.
In the Editor, first create an empty list:
nums = [ ] (with nothing between the brackets)
Use a for loop to make a list of 100 random numbers, each selected from the values between and including 1 and 25. You must enter the range( ) size 100.
The loop block is:
♦ ♦nums.append( randint(1,25) )
Select <Fns…> List for .append( )
With your cursor inside the .append( | ) parentheses…
Select <Fns...> Modul random… randint( )
and add the values 1 , 25 for the two arguments.
Pay attention to the two right parentheses at the end of this statement, a common syntax error if you are just typing code. If you use the menus the parentheses are provided.
Add a print( ) statement to the program (after the for loop) to print the list after all the numbers have been created:
Note that this statement is dedented.
Run the program now to make sure it works. Re-running the program in the Shell will display a different set of numbers in each run. To quickly re-run a program:
- Select <Tools> then press [enter] or
- Select <Editor> then select <Run> by pressing [trace] twice.
Here’s a sample run.
Add code to your program to determine the average of the numbers. Try it yourself first. (Remember the last lesson!)
Display the minimum and maximum values in the list. (Hint: See <Fns…> Lists.)
Can you sort the elements? Check the Lists menu again!
Python has two tools for sorting a list:
nums.sort() arranges the elements of nums into ascending order:
(changes the list nums)
sorted(nums) returns a list that is sorted but does not change the original list. Use nums2 = sorted(nums) to keep the original list and make a new, sorted list named nums2.
nums2 = sorted(nums)
(does not change the list nums)
After sorting the list, it is now possible to determine the median (middle) value and the range (difference between minimum and maximum) of the data set.
Add statements to your program to display these values.
Note: If the length (size) of the list is an even number, then the median is the average of the two “middle” numbers.
Use the len(<list>) function found on <Fns…> Lists to determine the length (size) of the list.
Can you also determine the Q1(first quartile) and Q3 (third quartile) values?
Application: A Toss of the DiceDownload Teacher/Student Docs
In this Application, you will make a simulation of dice tossing using random numbers.
- Use randint() to simulate dice tosses
- Use a list to keep track of totals
- Analyze the totals
When you toss a pair of fair six-sided dice, the sum of the two dice will be a value from 2 to 12. Which sum is most likely? Least likely? Write a program to simulate the dice tosses and analyze the frequency of each of the eleven sums.
Start a new Python file (ours is named DICE) using the Random Simulations template as in the last lesson.
Use a list of 11 elements, all 0, to keep track of the 11 sums (2 …12). An effortless way to create this list in Python is:
totals =  * 11
This means “make a list of 11 elements, all 0.” The multiplication sign ( * ) in this instance means “replication.”
(Try this expression in the Python Shell to see that it works.)
Use an input statement to ask how many times to toss the dice:
trials = int(input(“# of trials?”))
You can find # and ? on the <a A #> screen or
[ 2nd ] [ 3 ] gives the # sign
[alpha] [ (-) ] gives the ? symbol
Now write a for loop to perform each trial (dice toss):
for i in range(trials):
In the loop block, “toss the dice.” Use two variables, die1 and die2. Assign each a random integer from 1 to 6. Try it yourself first, and then move to the next step.
Did you write = randint(1, 6) for each?
Add the two die values together:
sum = die1 + die2
The sum ranges from 2 to 12 but the index of the list totals ranges from 0 to 10. We must subtract 2 from the sum to get the proper list index. To add 1 to the corresponding element in the list of totals looks like this:
totals[sum - 2] = totals[sum - 2] + 1
Yes, type this in by hand!
Tip: You can type the alpha characters first and then go back and fill in the symbols and numbers.
You may recognize this statement as a counter like c=c+1. Each element of the list is a separate counter.
That’s it for the loop block. When the trials are complete, we want to see the list of totals.
Dedent (un-indent) to the beginning of the next line, and print the totals list:
Test the program now. When you run the program, try a small number like 10 for the number of trials. Check to make sure the sum of the elements in the list is 10. You will probably not get these same numbers (they are random, right?), but the sum of the numbers should equal the number of trials. Re-run with the same number of trials, and you will see a different list.
When you are satisfied that the program runs as expected, try a large number of trials, say, 500, 1000, 5000. Which element of the totals list is the largest? Smallest?
When you are satisfied that the program runs as expected, try a large number of trials, say, 500, 1000, or 5000 or more.
Which element of the totals list is the largest? Smallest?
Your task: Write a for loop that divides each value in the list by the number of trials. Print the result. What is the significance of these numbers?
for i in range(11):
You might want to round the long decimals to a fewer number of places. What would be appropriate? Use round(n, #places).
- Skill Builder 1
- Skill Builder 2
- Skill Builder 3
Unit 5: The TI Modules
Skill Builder 1: The Plot ThickensDownload Teacher/Student Docs
In this lesson, you will create a scatter plot of the dice totals from Unit 4 Application using the ti_plotlib module.
- Introduce ti_plotlib
- Make a scatter plot
- Adjust the window
In the Unit 4, Application you made a simulation of tossing two dice and logging the experiment’s totals in a list. Here you will continue with that program and see how easy it is to make a scatter plot of that data using Python.
Rather than starting from scratch, load the dice project from the Unit 4, Application — we called it DICE.
You can make a copy of your program in the FILE MANAGER by pointing to your DICE program name and using:
<Manage> Replicate Program…
Type a new name when prompted. We’ll use DICEB.
Your DICE program should resemble the image shown here. After the first for loop, there is a list called totals that contains 11 values representing the number of times each total from 2 to 12 occurred in your trials.
It looks similar to this for 100 trials:
totals = [ 1, 6, 5, 9, 15, 13, 19, 13, 9, 5, 5 ]
Your numbers will vary.
The second for loop calculates and then prints the experimental probabilities. We will not be concerned with that loop in this project.
To create a graphical plot of the data that the program generated, you need to import another custom TI module. At the top of your program, below “from random…,” add the following import statement:
import ti_plotlib as plt
You can get this entire statement from <Fns…> Modul ti_plotlib.
Note: This form of import requires the prefix plt. in front of all of the ti_plotlib functions, and that will be provided when you select a function from the menu.
Scroll to the bottom of the program (below print(totals)).
To make a scatter plot we need two lists, an xlist and a ylist. totals is going to be the ylist. For the xlist, we use the 11 possible sum values:
sums = [2, 3, 4, 5, 6 , 7, 8, 9, 10, 11, 12]
There are other, clever ways of making this list, but just typing it in is fast and simple.
Now we can set up and display the scatter plot of (sums, totals).
Setup statements are taken from <Fns…> Modul ti_plotlib Setup.
The order of the functions on the menu illustrates the order in which they should appear in your code, and all Draw functions should follow the setup functions.
The setup we’ll use here are the statements:
- plt.cls() to clear the Shell screen for plotting
- plt.window( , , , ) to establish the viewing window
The window settings depend on the data. Use -5,15 for the x-axis and 10,1000 for the y-axis (we plan on tossing a lot of dice).
- plt.axes( )
The choices for the “mode” appear on a sub-menu. Select “on” to see the axes and window settings.
To make the scatter plot, from <Fns…> Modul ti_plotlib > Draw menu select:
plt.scatter(xlist, ylist, "mark")
- For mark, choose one from the four that are offered on the sub-menu; we chose the circle
- For xlist, type sums
- For ylist, type totals
and from <Fns…> Modul ti_plotlib setup menu choose:plt.show_plot() to pause the display until [clear] is
Run the program. Enter 1000 for the number of trials.
Does your plot look something like this? It may not match exactly since the dice are random.
Press [clear] to exit the plot screen and return to the Python Shell.
Try again with a larger number of trials.
Consider adjusting your window values.
Reminder: To “break” a running program press the [on] key.
You can customize the window for the number of trials:
In the plt.window( ) function change ymax to 1.1*max(totals).
This image shows 50000 tosses with this change as the program automatically adjusts the ymax value.
Note that we only added five new statements to the program to make the plot!
Skill Builder 2: Drawing with PythonDownload Teacher/Student Docs
In this lesson, you will transfer data between the Python environment and the TI-84 Plus CE Python graphing calculator environment.
- Work with store_list(), recall_list()
- Export a list to the calculator for further analysis.
The Python App is a separate system included in the TI-84 Plus CE Python graphing calculator. The most obvious change is the inclusion of lowercase characters.
But these are two separate “worlds.” The calculator world knows nothing about the data in a Python program, and the Python world knows nothing about the variables in the calculator.
It’s as if Python is a separate entity in the calculator. But there are special TI-developed functions in Python that let you transfer data between the two worlds (like teleporting).
In the last lesson, you wrote a program to generate data from dice tossing. We can use that program now to demonstrate the transfer of data from the Python world to the calculator world.
Recall the original DICE program you wrote in Unit 4, Application. The name is DICE, and the complete code is shown in this image.
Make a copy of this program in the <Fns…> Files FILE MANAGER.
Select the “DICE” file, and select <Manage> Replicate Program.
Ours is now named DICEC.
In your new duplicated program, you will use a function that is part of the ti_system module, so at the top of your program add the statement:
from ti_system import *
At the end of the program, when the totals list is complete, add this new function that sends the contents of the list to the calculator’s RAM:
store_list( “ ”, )
found on <Fns…> Modul> ti_system.
See the next step for completing the statement.
The store_list(““ ,) function requires two arguments. Both of them are the names of lists:
- Inside the quotes (the first argument) type the name of a TI-84 Plus CE Python list*
- After the comma, type the name of the Python list in this program to be transferred; in this case: totals
*Note: The TI-84 Plus CE Python list name must conform to the TI-84 Plus CE naming conventions for lists:
- All UPPERCASE
- Five characters or less
- Must begin with a letter
- Can be one of the built-in lists (L1 ... L6). Use a number from “1” to “6” in the quotes.
So, to meet these constraints, our TI-84 Plus CE Python list is called TOTLS.
Run the program. If you see something unusual then there is probably something wrong in your code. Nothing new should happen on the screen, but …
Quit Python (press [2nd] [mode]) and answer <Ok> or press [enter]).
From a blank line on the home screen, press [list]([2nd ] [stat]) to see the names of lists in your device. Below the built-in lists L1 … L6, you see your named lists and TOTLS is among them (in alphabetical order).
Your list names will likely look different than what is shown here. Select this list and, on the home screen, press [enter] to see its contents.
Now that you have the data in your TI-84 Plus CE Python graphing calculator world you can perform graphical and statistical analysis on it using the calculator tools with which you are already familiar.
We will demonstrate a graphical example next.
To make a scatter plot of this data you also need a list of sums.
Press [stat] Edit and enter the numbers 2 …12 into one of the lists. We use L1.
Set up a [statplot] found above [2nd] [y=] of TOTLS versus L1 as shown.
Turn Plot1 On. The Type: will be scatter plot, the first icon.
To get the list name L1 as the Xlist press [2nd ] .
To get the list name TOTLS as the Ylist press [list], scroll down to the name and press [enter].
Verify that your settings match the screen here. Then …
Press [zoom] ZoomStat to see the scatter plot. Yours should be similar to this but not exactly the same.
So, with little effort you can program a simulation using Python, transfer the data to your TI-84 Plus CE Python, and perform all the graphical and statistical analysis in your calculator using the tools you already know about. 😊
Skill Builder 3: GraphingDownload Teacher/Student Docs
In this lesson, you will use the ti_plotlib to graph a function. That is, you do not need to leave the Python world to create a graph of a function.
- Create a connected graph of plotted points
Let’s take a look at the Plotting (x,y) & Text template when starting a New program. It gives not only the necessary import statement, but also a whole demo program.
Notice line 3 of the program contains two list assignments but there’s no data in the lists.
x = [ ]; y = [ ]
x = [1, 2, 3 ]; y = [1, 2, 3 ]
You can use any numbers, but the lists must have the same number of elements.
When using the <Setup> functions of ti_plotlib (.cls(), .window(), .labels(), .grid() and .axes()) the order in which these statements are written matters so they are inserted automatically in the code in the proper order for demonstration.
After entering data in the lists x and y the program will run.
The last statement,
causes the plot to remain on the screen until the [clear] key is pressed. Without it, the Shell prompt appears. (Test this by placing a comment sign in front of the statement, and run the program again.)
Run the program to see the graph. Not quite what you are expecting? The points are plotted but they are not connected. Let’s connect the dots.
Press [clear] and return to the <Editor>. On the next-to-last line, change the word .scatter to .plot by deleting “scatter” and typing “plot.”
plt.scatter(x, y, ”o”) becomes plt.plot(x, y, ”o”)
The plt.plot(xlist, ylist, ”mark”) function is on the menu right below .scatter, but it is simpler to just edit the line rather than replace it.There is also a function to plt.plot( ) a single point but our x and y are lists, not numbers.
Run the program again and see that the three points are now connected with segments.
Write a program using ti_plotlib that will graph any defined function.
Start a new program, AGRAPH (so that it appears near the top of your Files list) and use the <Type> Plotting (x,y) & Text.
Change the word “scatter” to “plot” on the next-to-last line as before.
Below the import statement define a function to graph. This will make it easy to change the function later to graph any function.
We moved the rest of the code off the screen to be less distracting.
Get both def and return from <Fns…>
Give the function a name (we use f) and an argument (we use x)
After return, write the function expression (we use x**2):
♦ ♦return x**2
Remember to dedent to the left edge of the screen.
Below the x=[ ]; y=[ ] statements add some blank lines. Here’s where you will build the two lists one element at a time.
Write a loop structure that starts at xmin and goes up to xmax in small steps. Since these steps might not be integers a for loop is not appropriate because the for loop only allows integer arguments. Use a while loop:
a = plt.xmin
while a <= plt.xmax:
xmin and xmax are found on <Fns…> Modul ti_plotlib Properties
In the loop body build the two lists x and y using the .append() function.
♦ ♦x.append( a )
♦ ♦y.append( f(a) )
Recall that .append( ) is found on <Fns…> List.
Now add a value to the variable a so that it eventually increases to xmax. Let’s start with
♦ ♦a += 1
and see how it looks. You can come back and edit this increment value later to see its effect on the graph.
Recall that a += 1 is the same as a = a + 1.
Run the program. You will see an error message, the most important of which is the last statement: Invalid grid scale value. This error occurs because auto_window() looks at the lists x and y and sets up a window that fits all the data on the screen, but the .grid() function cannot make that many grid lines. There are several ways to fix the problem. Try it yourself before looking at the next step.
Some ways to fix the error:
- Eliminate the .grid() (make it a #comment)
- Change the .grid() values to allow the grid to be drawn
- Set the window and grid by yourself rather than using auto_window
Run the program. Do you see the graph shown here? Something similar? If so, congratulations! Share your success with a friend. You have graphed a function! Now for the extensions.Notes:
- If your graph does not appear or quickly disappears be sure that you have the plt.show_plot() function at the end of your program. This statement pauses the program until the [clear] key is pressed.
- If your program is stuck in an “infinite loop” press [on] to break the program. Check the while loop body to be sure that the variable a is being changed. We use a+=1 at the bottom of the loop. You can use other values than 1 but eventually the variable a must eventually exceed xmax so that the loop can end.
Extension. There are a lot of ways to embellish the graph of a function:
- Add Color
- Adjust dot spacing (change the increment)
- Adjust dot size (o, x, + and . are the four dot styles)
- Change line thickness (pen)
- Use custom window settings
- Change the function
- Graph multiple functions on the same screen
Use the ti_plotlib module features to enrich the appearance of your graph. A sample is shown here. Once you have the core code, enhancements are easy.
Note: For trigonometric, log, and other special functions, you have to use
from math import *
The trig keys ([sin] [cos] [tan]) all invoke the Trig menu and [log], [ln], [ex], and [10x] bring up the Python functions as well.
Application: Pi DartsDownload Teacher/Student Docs
In this application, you will create a simulation that (eventually) approximates the value of pi, the ratio of the circumference of a circle to its diameter — about 3.14159.
- Use random decimal numbers (uniform)
- Use a while not escape() loop
- Plot points on a “dart board”
- Display text on a plot screen
You have a square dartboard measuring 2 units on a side with a circle inscribed in the square. Toss some darts at random onto the board. Some will land inside the circle (“hits”), and some will land in the square but outside the circle (“misses”).
The ratio of the “hits” to the total number of darts tossed is a function of the areas of the two shapes: circle/square.
The area of the square is ___.
The area of the circle is ___.
The ratio circle/square is ___.
Write a program to perform this simulation, and approximate the value of pi.
- Use escape() to end the program
- Select two random decimal (real) numbers between -1 and 1 and if the point is inside the circle count it as a hit
- Plot the point on the graphics screen in a special color
Begin a new program (PIDARTS) and get the three import statements from the <Fns…> Modul menus.
Use these plotlib setup commands to create a nice graphics screen.
Select these commands from <Fns…> Modul ti_plotlib.
plt.cls() #clear the screen
plt.window(-2, 2, -1.5, 1.5) #a nice viewing window
plt.axes(“axes”) #show only the axes
Make two variables for counting the darts and counting the hits.
Initialize both to 0.
hits = 0 # of darts inside the circletotal = 0 # of darts tossed
Write the loop that terminates when [clear] is pressed:
Select while not escape():
from the ti_system module menu.
The first action in the loop is to toss a dart. Just add 1 to the total variable:
♦ ♦ total += 1
This statement is indented because it is in the loop body.
Note: total += 1 is the same as total = total + 1 but requires less typing.
Now choose two random decimal numbers between -1 and 1. They must be floating-point numbers, not integers, so use the uniform() function:
♦ ♦x = uniform(-1, 1)
♦ ♦y = uniform(-1, 1)
The function uniform() selects a random floating-point value (includes decimals) between min and max.
Find uniform() on <Fns…> Modul random.
Set the plot color to black using plt.color(0,0,0)
found on the <Fns…> Modules ti_plotlib Draw menu.
if the dart is inside the circle …
Use the condition x*x + y*y <= 1 because all the points inside the circle are within 1 unit of the origin. The distance of a point from the origin is given by d = sqrt(x**2 + y**2) from the Pythagorean Theorem. But the square root of 1 is 1 so we do not need the sqrt function.
Count it as a “hit”:
♦ ♦ ♦ ♦hits += 1
Change the plot color (we use orange for a hit):
♦ ♦ ♦ ♦plt.color(255, 100, 0)
Note that these statements are indented even more because they are inside the if block which is inside the while block.
Dedent (un-indent) the next line to exit the if block but remain in the while block. Plot the point.
♦ ♦plt.plot(x, y, ”mark”)
from <Fns…> Modules ti_plotlib Draw.
You will choose the “mark” on a sub-menu. If you want to change the “mark” later on take note because the menu only appears once. The marks are o, x, + and .
You will have to fill in the variables x and y in the code.
Run the program now. You should see some dots appear. After a while, press [clear] (that’s the “escape” key) and you will return to the Shell.
Our screen is lacking some information! Where’s pi?
In the Editor you can use plt.text_at( ) to display “text,” the value of a variable, or the result of an expression like hits/total.
plt.text_at(1, str(hits), “left”)
would show the value of the hits variable in the upper left corner of the screen. str( ) is needed to convert the hits value into a string for the text_at( ) function.
♦ ♦plt.text_at(1, str(hits), “left”)
right below the plt.plot( ) statement produces the number seen in the upper left corner. But the color used is not always the same. Sometimes it is black, and sometimes it is orange. Add another plt.color( ) statement just before the plt.text_at( ) statement to fix the color.
There are 12 rows available for text_at( ). Add more information to the display: the total number of darts tossed and the expression hits/total * 4.
Why multiply by 4?
Note: The text_at( ) function impacts the entire line, not just the area where the text is displayed, so you need to leave room at the top and bottom of the screen for the text.
- Skill Builder 1
- Skill Builder 2
- Skill Builder 3
Unit 6: micro:bit
Skill Builder 1: The displayDownload Teacher/Student Docs
In this lesson, you will write your first python programs to control the micro:bit display in different ways. This lesson has two parts:
- Part 1: Alien Encounter
- Part 2: Displaying images
- Control the display on the micro:bit board using .show( ), .scroll( ) and .show(image)
- Control the speed of the display using sleep(ms) and delay=
- Writing a loop structure
Before you begin, be sure that:
- You are using a TI-84 Plus CE Python with OS 5.7
- You are comfortable programming in python and/or you have already completed Units 1 through 5.
- Your micro:bit is connected to your calculator and lit.
- You have followed the set-up directions and file transfers in the micro:bit Getting Started Guide:
and thus have the TI runtime file on the micro:bit and the latest microbit modules in your calculator
This setup process should only have to be done once but keep informed periodically about updates/upgrades.
From the home screen (Quit the Python App) you can check your calculator to be sure that the appropriate files are installed: press [2nd] [+] for [mem], select Mem Management > AppVars and scroll to the ‘M’ section to find MICROBIT and the MB_* support files shown.
Note: there are more than those displayed in this image: a total of 11 (version 1) or 13 (version 2) micro:bit AppVars.
If all is good and the setup has been done correctly, your micro:bit should look like this when it has power from the calculator:
The display on the micro:bit is showing the TI logo, an icon of the state of Texas with a bright spot near Dallas, the home of Texas Instruments, Inc.
Part 1: Alien Encounter
Of course, as with every other first programming experience, you will start with displaying a message on the micro:bit display. In the Python Editor start a <New> program (we name it GREETING).
In OS version 5.7, when selecting <Fns…> Modul, a soft key appears called <Add-On> which gives access to additional TI-developed modules. (if you don’t see this, you need to update to OS 5.7)
Tip: If the message ‘micro:bit not connected’ ever appears, just unplug the micro:bit and plug it in again (reset).
Select <Add-On> and see some additional modules that are available, some of them shown here. Your list may differ but should include microbit. Select from microbit import * to paste that code into your program.
In the Editor, the presence of this statement adds a new option to the bottom of both the <Fns…> Modul menu and the [math] menu: Micro:bit…
As you add features from Micro:bit this menu will grow!Note: [math] is a keypad shortcut for <Fns…> Modul but does not display the <Add-On> soft key.
The Micro:bit… sub-menu contains all the tools necessary for programming the micro:bit in separate sub-modules.
Each of these menu items will paste its own import statement since the tools are all in separate Python modules (AppVars). If you are using a micro:bit version 1 there are fewer items on this screen.Select the Display menu…
After selecting Display, you see a new import statement in your program:
from mb_disp import *
Look at the [math] menu again: There is now a display… menu item added to the bottom of the list. Select display…
The display… menu (shown) contains the functions that control the display on the micro:bit, the 5x5 grid of red LEDs in the center of the board and more.
Press [2nd ] [alpha] to turn alpha lock on and press [+] for a quotation mark. All letters typed will be lowercase. For uppercase, press [alpha].
Note: There are two optional arguments that you can add:
display.show( , delay = 400, wait = True)
delay=(time in milliseconds) controls the speed of the display.
wait= (True or False) tells the micro:bit/calculator to finish displaying before moving on to do something else.
Each parameter can and should be edited to see their impact and each may be specified using their keyword. This is recommended, but not required.
<Run> the program and watch the display on the micro:bit.
You will see the letters of your message appear, one letter at a time, on the display. The lowercase letters ‘e’ do appear twice but you cannot distinguish two of them.
A better method for displaying long messages is:
which is also found on the [math] display… menu.
Make the previous .show() statement a #comment. Place the cursor at the beginning of that line and press [2nd]  to insert a ‘#’ and then run the program again.Yes, you can also simply change .show to .scroll by typing.
Note: .scroll() also supports the optional delay= and wait= arguments.
The display.scroll( ) function causes the message to scroll smoothly from right to left like a banner. delay controls the speed of the scrolling. wait tells the calculator and micro:bit to wait until the scroll is done before moving on to another instruction. Try other delay values to see the effect on the scrolling.
display.scroll( , delay = 100, wait = True)
Part 2: Displaying images- Be.Still.My.Beating.Heart
This section shows you how to display images on the micro:bit.
Select <Files> and make a new program called HEART.
In the Editor, add the two import statements as before:
from microbit import *
from mb_disp import *
First, get the microbit module from <Fns…> <Add-On>
Then press [math] Micro:bit… for display…
display.show( … )
Again, this statement is found on:
from the [math] display… Images sub-menu.
Note: there are 36 Images to choose from and you can design your own using var=Image( … ) found on the Display sub-menu. See micro:bit documentation online for information on this feature.
In case you have not noticed…to cut down on keypresses, the menu system allows for up-arrow and left-arrow ‘wraparound’, so, for example:
Select [math] then up-arrow to display…
The string “Image.Heart” is inserted into your code as shown in this screen.
<Run> the program. Do you see the heart ❤?
This display remains on the micro:bit until something takes its place, even after the program is done. To restore the original TI icon, reset the micro:bit. There is a ‘reset’ button on the back of the micro:bit or you can unplug and re-plug from the calculator. Or just leave it alone.
Go back to the Editor and add another display.show( ) statement to show the small heart:
Be sure to get the display.show( ) statement first, then paste the “Image.HEART_SMALL” string. You can find this ‘small heart’ string on the same Image sub-menu right below HEART.
<Run> the program again. It quickly displays the large heart and then displays the small heart that looks like this.
Make a loop: To get the two hearts to blink repeatedly (‘beat’), embed the two display statements in a loop. Before the two display statements insert:
while not escape( ):
found on [math] ti_system…
and indent the two display statements so that they form the loop body.
You also need to import ti_system in order to use this special while statement. Place that import statement at the top of your code.
Important Tip: new to Python? Indentation is critical in Python programs. This is how python interprets loop blocks and if blocks. If the two display statements are not indented the same number of spaces then you will see a syntax error. Use the [space] key ([alpha] ) or select <Tools> Indent►to indent both lines the same amount. Indentation spaces are indicated in this Editor as light gray diamond symbols (♦ ♦) to help with proper indentation.
<Run> your program again and watch the Beating Heart! Press the [clear] key to end the program.
Tip: if you ever think your program is stuck in an infinite loop, press and hold the [on] key on your calculator to ‘break’ the program. This could happen if you use while True:. These lessons avoid that type of structure by using the while not escape(): loop.
To control the beating heartrate, add the delay= and, optionally wait=, argument and adjust the values in these two display commands as shown here. Remember that the delay value is in milliseconds.
Note: some blank lines have been removed from the program in this screen to show the entire program.
Change both wait= parameters to False to see how fast the heart blinks. False is found on <a A #>. wait = True tells the micro:bit to complete the task before going to the next task (like ‘pause’ or ‘sleep’). When False it goes immediately to the next task and ignores the delay= value.
Skill Builder 2: The ButtonsDownload Teacher/Student Docs
There are three parts to this lesson:
- Part 1: Investigate the button functions
- Part 2: Use a button to generate some data
- Part 3: store data in a list using buttons and transfer the list to the TI-84 Plus CE.
- Read and process the A and B buttons on the micro:bit
- Observe the difference between .was and .is
- Investigate collected data from the micro:bit
- Transfer data from python to TI-84 Plus CE
Add the ti_system module to your code using [math] ti_system:
from ti_system import * From <Fns…> Modul select <Add-On> microbit to get the statement:
from microbit import *
Then start a loop:
while not escape():
The special while loop can be found under [math] ti_system… or <Fns…> Modul ti_system…
Important: The microbit import must come after the ti_system import statement!
Handy Tip: Replicate this file as MBSTART and use it as a template for all other micro:bit programs. Just replicate the file using the name of a new program!
To use the micro:bit buttons A and B, you must first import the buttons module.
Place your cursor below all existing import statements at the top of your code (on a blank line).
Press [math] and select Micro:bit…. Choose Buttons and Touch Logo. This inserts the import statement from mb_butns import *
It also adds a new item to the <Fns…> Modul (or [math]) menu below Micro:bit….
To test button A, in the while loop body add the following if: structure:
♦ ♦if button_a.was_pressed():
♦ ♦ ♦ ♦print("button A")
if is found on <Fns…> Ctl and automatically adds leading spaces below it for further indentation of the block.
The condition button_a.was_pressed() is found on the menu item:
[math] buttons and touch…
Select .was_pressed() under the button A menu.
Remember to leave the colon at the end of the if statement:
print( ) is on <Fns…> I/O
Type the text “button A” inside the print( ) function.
Note: .is_pressed() will also be discussed later.
<Run> the program. It looks like nothing is happening. Press and release button A on the micro:bit. You will see ‘Button A’ appear on the calculator screen. Each time you press and release the button the text will appear as in this image.
Reminder: if you think your program is stuck in an infinite loop press and hold the [on] key on your calculator to ‘break’ the program.
Press [clear] to end the while loop (and the program) and then return to the Python <Editor>.
Add another if statement to check button B using the condition button_b.is_pressed(). You will see how .is_ and .was_ differ soon.
♦ ♦if button_b.is_pressed():
♦ ♦ ♦ ♦print("Button B")
Tip: again, pay attention to the indentations!
<Run> the program again. Try both buttons A and B.
Tap each button and press-n-hold each button.
You will see ‘Button B’ repeatedly displayed as long as button B is held down, but not ‘Button A’. There is a difference between .was_pressed() (which needs a release of the button to be reset) and .is_pressed() which just checks to see if the button is down at the very moment that the statement is processed.
Note: if you tap button B quickly, the program may not display Button B since the button is not down at the very moment the if statement is being processed.
Part 2: Use a button to generate some data
Let’s use a button to toss a die (a cube numbered 1..6 on each face). When button A is pressed, assign a random integer from 1 to 6 to a variable. You can use ‘button A was pressed’ or ‘button a is pressed’. Try both to see the difference.
Display the value of the die on the micro:bit only. Try it yourself before looking at the next step. We will use the current program and add code to simulate the die toss.
Can you determine what number is on the bottom of the pictured die?
Add the two statements highlighted as shown in the image:
from random import *and randint( , ) are both found on
The variable die and the arguments ♦ ♦ ♦ ♦die = randint(1, 6) are typed in manually. Notice that the statement is indented to be part of the if button_a… block.
Again, be careful about the indentation.
Now note these two new highlighted statements in the image again. After the value of the die has been established, we would like to display it on the micro:bit.
First, in order to use the micro:bit display features, you must import the display module (the top statement). Get it from [math] Micro:bit….
Then add the statement:
♦ ♦ ♦ ♦display.show(die)
below the die= statement to show the value of the die on the micro:bit.
Micro:bit display commands are found under [math] display…
<Run> the program again. When you press button A you see ‘Button A’ on the handheld screen and the die value on the micro:bit display changes… but not every time! Sometimes the random number selected is the same as the last number and… that’s OK. The presses are ‘independent events’.
Part 3: Collecting data
Tossing all those dice with just a button press is nice, but for further study it would be helpful to store all those values so that you can interpret the data: which number occurs most often? What is the average number? and so on.
In the next step, you will add statements to the program to:
- Create an empty list
- Add (.append) the die value to the list
- Store the list from python to the TI-84 Plus CE system for analysis
Begin with an empty list. The empty list assignment belongs at the start of the program, before the while loop:
tosses = [ ]
The variable name, tosses, is typed in. The square brackets are found on the keypad, on <a A #>, on [list] ([2nd] [stat]) and on <Fns…> List.
After the die value is determined, it is added to the list with the statement:
At the end of the program, after the while loop ends, the final list is stored to a TI-84 list:
the store_list function is on [math] ti_system…
Note that this statement is not indented at all so that it is not inside the while loop but is only executed once at the end of the program once [clear] is pressed. This function stores the Python list tosses over to the CE list TOSS. The CE list “TOSS” must be UPPERCASE and less than 6 characters.
**Again, pay attention to the indentations, especially store_list() which is not indented at all so that it is not part of the while loop.
Note: the display.show( ) statement has been modified to include the optional delay= and wait= arguments as explained in the previous lesson.
Note: You may need to add a sleep(100) statement to the while loop (just before the if statement) if button A does not respond.
Button B is not used (yet). Can you use button B for something special here?
When you run the program now:
- if you used .was_pressed, press and release button A many times (You should see ‘button A’ on the calculator screen and numbers on the micro:bit display).
- if you use .is_pressed, hold button A down.
Press [clear] to end the while loop. Your python program had a list named ‘tosses’ and now your TI-84 CE also has a list named ‘LTOSS’. These are two separate lists in two separate environments.
Quit Python and set up a [stat plot] histogram of TOSS. You can also perform a 1-var Stats analysis. Do you notice a pattern? Try more tosses*!
*Note: due to memory constraints, the store_list( ) function is limited to lists of 100 elements maximum.
Skill Builder 3: Collecting lightDownload Teacher/Student Docs
In this lesson, you will monitor the light sensor on the micro:bit and store the data in a TI-84 Plus CE list for further analysis.
- Read and display the brightness sensor on the micro:bit
- Transfer data from python to TI-84 Plus CE
- Investigate collected data from the micro:bit
The micro:bit can read the ambient light level using the display LEDs. Yes, the display LEDs can also be used as an input device!
In a new program (LITE) add the usual imports and the while loop.
Add an import statement at the top to access the micro:bit display menu:
from mb_disp import *
In the while loop body, write the assignment statement:
♦ ♦b = display.read_light_level()
Type b and get = .read_light_level() from [math] Display…
Add a print statement to see what the function produces:
♦ ♦print(“b = “, b)
<Run> the program and point the display side of the micro:bit at a light source. It does not matter what is showing on the display. Move the micro:bit toward and away from the light and observe the changing values on the TI-84 screen. You should see values varying between 0 and 255.
Note: if you do not see changing values as in this image, add a sleep(100) statement to the loop to slow things down.
As you probably expect, the further from the light source, the lower the light level value. Now you will add code to the program to collect the light level data. Then you can create a scatter plot of light vs. time.
Press [clear] to end the program and go back to the <Editor>.
times = [ ]
brites = [ ]
Find the square brackets on the keypad, on <a A #>, on <Fns…> List or on [list]. You can use shorter variable names to save on typing (like ts and bs).
Also before the while loop, add a statement to start a ‘time’ counter variable (t) at 0:
t = 0
Avoid using the word ‘time’ as a variable because there is a time module. It is a good practice to pluralize list names because they contain many values.
In the loop body, after the print statement, add a statement to increase the timer variable t. We will use a one second time interval between light readings, so use:
♦ ♦t = t + 1
Note: in Python you can also write this statement as: t+=1
Add the values of t and b to their respective lists using the statements:
.append( ) is found on <Fns…> List and is pasted after typing the variable name.
These statements add the current b (brightness) value and t (time) value to the end of the lists.
To control the timing of the sampling, add:
after the two .append statements. This pauses data collection for one second between each sample.
sleep( ) is included in the microbit module and is modified to use milliseconds.
After the while loop ends, store the two Python lists into TI-84 Plus CE lists using store_list( ) found on [math]ti_system….
The TI-84 list names (the arguments in “QUOTES”) must be 5 UPPERcase letters or less. We use BRITS and TIMES for those lists. The second argument of store_list( , ) is the Python list variable to store.
<Run> the program. Start with the micro:bit close to your light source. An exposed light bulb or a smartphone flashlight work well. Slowly but steadily move the micro:bit away from the light at a constant rate until the brightness reading is less than 10.
Press [clear] to end the program.
Repeat the process until you feel that you may have ‘good’ data. Displaying the data on the calculator screen using print( ) or disp_at( ) may be helpful. Sample data in this image of the TI-84 Plus CE Stat Editor shows some collected data in the lists TIMES and BRITS.
Application: Toss the diceDownload Teacher/Student Docs
In this Application you will write a program to collect data using the micro:bit and run the program while observing a dot plot grow on a graphics screen using ti_plotlib.
- Write a micro:bit data collection program
- Create a dynamic plot of the collected data as the program is running
This Application is a compilation of the micro:bit skills you learned in the previous Units:
- write a program that uses a button to collect some data,
- display the data on the micro:bit,
- show a growing dot plot of the collected data and then store the lists as TI-84 Plus CE lists for further study and analysis.
The micro:bit can act as a 2-dice roller and display two values (sequentially). The calculator can display a growing dot plot of the sums recorded at the same time.
Write a program that conducts the dice tossing experiment and collects the data. At the end of the program store the data into CE lists for further study and analysis on the calculator. Let’s get started…
Start a new program called DICEPAIR.
You will need a bunch of Python tools for this program so there are quite a few imports that will take place.
- ti_system for escape( )
- random for randint( , )
- ti_plotlib for the Python graphics
- microbit for the micro:bit
- mb_disp for the micro:bit display
- mb_butns for the micro:bit buttons
Tip: as you develop a program from scratch you will find that you need more import statements than you originally thought. It’s fine to go back and add them as needed.
Use button A to toss the dice and button B to ‘reset’ the data collection and start over. It will be convenient then to have a ‘setup’ subroutine that can be used in different parts of the program to set up the plot screen in the calculator.
Start your code with a def setup( ): function.
This function performs the setup commands for plotting as indicated by the.plt prefix.
Find these commands on [math] ti_plotlib.
All these statements are indented to form the function body.
Remember that the order of these setup commands is important and they should be used in the order that they appear on the menu.
The color statement is on the Draw menu. We chose black axes and purple dots.
Begin the main program using a #comment as an indicator.
Create two lists:
ttls and ttls are not possible sums but act as ‘placeholders’ so that the indexes match the element contents. When the sum of the dice is 2 we will increment element sums.
Note: To produce a scatter plot we need two lists. ttls is the first list and sums is the second list.
Now ‘call’ the setup( ) function you defined above to prepare the calculator screen for plotting.
Begin with the usual…
while not escape():
♦ ♦ if button_a.is_pressed():
Why did we choose .is_ instead of .was_ ? Think about the difference, or just wait and see…
Remember, pressing button A:
- tosses the dice
- displays them on the micro:bit
- calculates the total
- increments (adds 1 to) the proper element of sums
- produces a scatter plot.
Try writing the code for button A now.
Here is most of the code for button A. One feature is missing: displaying the two dice on the micro:bit. That is left as a project for you.
Hint: The command
display.show(<variable>, delay=400, wait=True)
displays the value of the <variable> on the micro:bit. You will need to display two values (each die).
You can test your program as written so far (even without the display. statements). It should show a scatter plot on the calculator screen as you hold down button A (fast). That’s why we chose .is_.
If we used .was_ then we would have to click and release button A to make each toss.
But wait… there’s more!
Press [clear] to end the program.
There are two more tasks:
(in addition to making the micro:bit display the values of the dice under button A)
- Button B should act as a ‘reset’ button: clearing the screen by calling setup( ) and set the sums list to all 0’s again. That’s only two statements in the if button_b… block as shown.
Note the use of the setup() function again.
- The final two lists should be exported to the CE for further study. You need two store_list( , ) statements (incomplete as shown), one for each list in the program.
Pay attention to the indentation.
Note: we used .was_ instead of .is_ for button B. Can you feel the difference?
After you have stored the two lists by pressing [clear] to end the loop and the program, quit the Python app ([2nd ] [quit]) and set up a scatter plot of TTLS, SUMS - the CE lists are all CAPS - as shown in this image.
- Skill Builder 1
- Skill Builder 2
- Skill Builder 3