10 Minutes of Code: Python
Explore the basics of Python with these short, easy-to-master lessons that include everything beginners need to get started and succeed.
Unit 1: Getting Started with Python
Skill Builder 1: Introducing the Python Apps
Download Teacher/Student DocsIn 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.
Objectives:
- Python overview
- Use Editor and Shell
- Run a program
- Edit a program
- Entering expressions in the Shell
Step 1
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.
Step 2
Let’s start learning about the Python environment. Press [prgm] and select Python App from the menu.
Step 3
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.
Step 4
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!
Step 5
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.
Step 6
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.
Step 6b
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.
Step 7
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
Step 8
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.
Step 9
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.
Step 10
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.
Select <files>.
Step 11
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.
Step 12
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.
Step 13
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, Expressions
Download Teacher/Student DocsIn 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.
Objectives:
- 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
Step 1
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>.
Step 2
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.
Step 3
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.
Step 4
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 screen
An 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.Step 5
- 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
Step 6
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.
Step 7
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?
Step 8
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.
Step 9
When you run this program, you now see:
x= 9 y= 34 z= -23
Note: If you get an error message or the wrong output, go back and edit the statement.
Skill Builder 3: Introducing the Python Function
Download Teacher/Student DocsIn this lesson, you will define a function and use the function to evaluate expressions. You will experience the purpose of indentation in Python Editor.
Objectives:
- Define a function
- Use the function in evaluating expressions
- Use the input() function
Step 1
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.
Step 2
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:
def f(x):
♦ ♦
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.
Step 3
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.
Step 4
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 [0] key, and the colon (:) is on the [.] (decimal) key.
Step 5
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.
Step 6
Step 7
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
Step 8
They are int(), float(), str() and complex().
Step 9
x=float(x)
or
x=int(x)
Try both and see the difference.
We chose float() in this example. Why?Step 10
<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.”
Step 11
Challenge. How would you change the code to get the value of x to appear inside the function's parentheses (instead of the letter x) like this:
f(4.0) = 27.0
Application: Two Functions Are Better Than One
Download Teacher/Student DocsIn this Application, you will make a second function and use both functions to investigate some of the mathematical properties of functions.
Objectives:
- Editing a Python file
- Copying a Python file
- Adding a function
- Evaluating function expressions in the Shell
- Creating an inverse function.
Intro 2
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.
Step 1
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.
Step 2
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.
Step 3
Using the [del], revise f(x) by removing the x**2 term:
f(x) = 3*x - 1Define g(x)
return -2*x - 4
Step 4
Turn each of the last three lines of code in the program into #comments:
Place the cursor at the start of the line.
Either:
Select [a A #]
Press [enter] on the # character.
Select [Paste]
Or:
just press [2nd ] [3] 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.
Step 5
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].
Step 6
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))
- Skill Builder 1
- Skill Builder 2
- Skill Builder 3
- Application
Unit 2: Input, Output and Functions
Skill Builder 1: A Tale of Two Means
Download Teacher/Student DocsIn this lesson, you will write a program that requires a mathematical function that is not part of Python’s ‘built-in’ tools.
Objectives:
- Use import for additional functions
- Write a program using the menus
- Examine a mathematical relationship
Step 1
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.
Step 2
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.
Step 3
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’Step 4
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.Step 5
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( )
Step 6
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)
Step 7
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 Formula
Download Teacher/Student DocsIn this lesson, you will use one of the program templates, create a function to evaluate and return a value, and explore the mathematical operators.
Objectives:
- Use a program template (Type:)
- Create a function for Heron’s Formula
Intro 2
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.
Step 1
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.Step 2
The filename entry screen now shows the template selected:
Math Calculations
at the bottom.
Step 3
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].
Step 4
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.
Step 5
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.Step 6
Finish the function by providing the return statement:
♦ ♦return area
found on <Fns…>. You must type the variable name area.
Step 7
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.
Step 8
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.
Step 9
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.
Step 10
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 Formula
Download Teacher/Student DocsIn this lesson, you will write and use a function that is used more than once.
Objectives:
- Review the midpoint formula
- Use uppercase in a variable
- Store the result of a function in a variable
- Return two values from a function
Intro 2
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
Step 1
In a new Python file (our file is named MIDPOINT), select <Fns…> and use the def function( ): template.
Name the function midpt( ).
Step 2
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.
Step 3
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.
Step 4
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)
Step 5
Now go back to complete the midpt() function.
Use two arguments. It is better to use two new variables as arguments:
midpt(a, b):
♦ ♦
Try completing the function now. Then compare your work to the next step.
Step 6
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…>.
Step 7
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 Horizon
Download Teacher/Student DocsIn this Application, you will write a program that determines the distance to the horizon from a given altitude.
Objectives:
- Use import for additional functions
- Write a program using the menus
- Use multiple units in one problem
Intro 2
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.
Step 1
Start a new Python file (we call it horizon).
Start with a comment explaining the purpose of the program. You can press [2nd ] [3] for the # symbol and turn on alpha-lock for the rest of the text. Remember that the space is on the [ 0 ] key.
Step 2
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.”
Step 3
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 #>.Step 4
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.
Step 5
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)
Step 6
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.
Step 7
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.
Step 8
You are almost ready … you still must print the answer.
print(leg2)
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.
Step 9
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
- Application
Unit 3: Conditions, if and while
Skill Builder 1: Collatz
Download Teacher/Student DocsIn this lesson, you will ‘branch’ out into the world of conditional programming. You will also investigate a mathematical theory that is (so far) unproven.
Objectives:
- Learn the relational and logical operators
- Learn the integer operators (% and //)
- Write programs using if statements and while loops
Intro 2
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.
Step 1
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: "))
Step 2
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 actionsfor 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.
Step 3
Insert the if.. else statement from <Fns…> Ctl.
Step 4
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] [0].
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]
Step 5
if (the number is even) :
♦ ♦(the “True” block)
is:
♦ ♦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.
Step 6
else: (when the number is odd — no condition here) :
(the “False” block)
is:
♦ ♦num = 3 * num + 1
Step 7
After the if.. else: structure, backspace to the beginning of a line (erase the indent characters) and write the print statement:
print(num)
Step 8
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.
Eventually.…
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.
Step 9
Place your cursor right below the input statement and above the If statement as shown in this image.
Step 10
On this blank line add the while statement found on
<Fns…> Ctl
You will see:
while :
♦ ♦
pasted into your program and your cursor is blinking on the colon.
Step 11
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.Step 12
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 :
Step 13
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 Waving
Download Teacher/Student DocsIn 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.
Objectives:
- Counter statement
- Accumulator statement
- While loop with a flag
- Calculating an average (mean)
Step 1
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…>.
Step 2
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.
Step 3
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.
Step 4
Question: Is -999 included in the total?
Answer: No!
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.
Step 5
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.
Step 6
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.Step 7
We use three print statements to report the results:
print(" Count = ", count)
print(" Total = ",total)
print(" Average = ",avg)
Step 8
A sample run of the program is shown.
Skill Builder 3: Press a key
Download Teacher/Student DocsIn 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.
Objectives:
- 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
Step 1
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.
Step 2
Now introduce a variable num = 2 just before the while statement.
Step 3
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.
Step 4
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.
Step 5
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.
Step 6
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.
Step 7
sleep(1)
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”).
Step 8
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.
Step 9
Extra: Change each 2 in the program to 0.5.
What happens?
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: FizzBuzz
Download Teacher/Student DocsIn this Application, you will write a program to illustrate the amazing ‘FizzBuzz’ phenomenon.
Objectives:
- Make a while loop that terminates in two ways
- Define a function that examines numbers for ‘divisibility’
Intro 2
FizzBuzz
Other requirements: The program should end when the esc key is pressed.
‘Divisibility’ is tested using the % operator (mod or remainder). |
|
Intro 3
There is one other form of the if statement you will find useful:
if <condition>:<true block1>
elif <condition2>: there can be many elif blocks
<true block2>   elif is short for ‘else if’
<more elifs?>
else:
<false block> this block is processed when none of the
others are true.
Step 1
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.
Step 2
Before the while loop, set up a variable that represents the counting numbers starting with 1.
Step 3
Use the if..elif..else structure found on <fns…> Ctl.
Remember that it works like this:
if <this is true>:
<do this>
<do this>
(there may be more elifs in here)
else:
<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.
Step 4
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.
Step 5
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
- Application
Unit 4: for loops and lists
Skill Builder 1: Home on the range()
Download Teacher/Student DocsIn this lesson, you will create your first of many for loops and examine the many advantages of iterations.
Objectives:
- Explore the range() function
- Use in to test for membership
- Write a for loop
Step 1
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.
Step 2
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
Step 3
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.
Step 4
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.
Step 5
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.
Step 6
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.
Step 7
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):
print(i)
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)
Step 8
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.
Step 9
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.
Step 10
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 Lists
Download Teacher/Student DocsThis lesson introduces you to Python lists, which are similar to, but not the same as, TI-84 Plus CE graphing calculator lists.
Objectives:
- 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
Step 1
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.
Step 2
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.
Step 3
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[3] (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.
Step 4
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[5] in a 5-element list.
List a looks like this:
Index: | 0 | 1 | 2 | 3 | 4 |
Element: | 5 | 6 | 7 | 8 | 9 |
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.
Step 5
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).
Step 6
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.
Step 7
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.Step 8
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.
Step 9
To add each value to the list nums, use the Python function:
nums.append(value)
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.Step 10
Print the list with the single statement:
print(nums)
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.)
Step 11
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).
Step 12
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 Randomness
Download Teacher/Student DocsIn this lesson, you will make a list of random numbers to investigate patterns.
Objectives:
- Use randint(a,b)
- Create a list of random integers
- Analyze properties of the list
Intro 2
Background
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 * [0] 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.
Step 1
For this project, when creating the <New> Python program, when entering the program name, choose Random Simulation from the <Type> menu.
Step 2
Our program is named RANDOM1 and the template provides a comment and the statement:
from random import *
Step 3
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.
Select <Esc>.
Step 4
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.
Step 5
Add a print( ) statement to the program (after the for loop) to print the list after all the numbers have been created:
print(nums)
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.
Step 6
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!
Step 7
About sorting
Python has two tools for sorting a list:
nums.sort() arranges the elements of nums into ascending order:
print(nums) unsorted
nums.sort()
print(nums) sorted
(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.
print(nums) unsorted
nums2 = sorted(nums)
print(nums2) sorted
(does not change the list nums)
Step 8
Extension
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 Dice
Download Teacher/Student DocsIn this Application, you will make a simulation of dice tossing using random numbers.
Objectives:
- Use randint() to simulate dice tosses
- Use a list to keep track of totals
- Analyze the totals
Intro 2
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.
Step 1
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 = [0] * 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.)
Step 2
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):
♦ ♦
Step 3
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.
Step 4
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.
Step 5
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:
print(totals)
Step 6
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?
Step 7
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?
Step 8
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?
Start with:
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
- Application
Unit 5: The TI Modules
Skill Builder 1: The Plot Thickens
Download Teacher/Student DocsThe TI-84 Plus CE Python system contains some special TI-developed modules. One of them that is useful for plotting data is ti_plotlib.
(Note: You can find additional activities for other ti_ modules in the [+] Python Modules section of TI Codes.)
Objectives:
- introduce ti_plotlib
- make a scatter plot
- adjust the window
Intro 2
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.
Step 1
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.
Step 2
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.
Step 3
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.
Step 4
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.
Step 5
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.
Step 6
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] ispressed.
Step 7
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.
Step 8
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 Python
Download Teacher/Student DocsIn this lesson, you will transfer data between the Python environment and the TI-84 Plus CE Python graphing calculator environment.
Objectives:
- Work with store_list(), recall_list()
- Export a list to the calculator for further analysis.
Intro 2
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).
Step 1
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.
Step 2
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.
Step 3
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 *
Step 4
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.
Step 5
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.
Step 6
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 …
Step 7
Quit Python (press [2nd] [mode]) and answer <Ok> or press [enter]).
Step 8
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.
Step 9
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.
Step 10
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 ] [1].
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 …
Step 11
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: Graphing
Download Teacher/Student DocsIn 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.
Objectives:
- Create a connected graph of plotted points
Step 1
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 ]
Step 1b
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,
plt.show_plot()
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.)
Step 2
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.
Step 3
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.Step 4
Run the program again and see that the three points are now connected with segments.
Step 5
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.
Step 6
Change the word “scatter” to “plot” on the next-to-last line as before.
Step 7
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):
def f(x):
♦ ♦return x**2
Remember to dedent to the left edge of the screen.
Step 8
Below the x=[ ]; y=[ ] statements add some blank lines. Here’s where you will build the two lists one element at a time.
Step 9
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
Step 10
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.
Step 11
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.
Step 12
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.
Step 13
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
Step 14
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.
Step 15
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 Darts
Download Teacher/Student DocsIn 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.
Objectives:
- Use random decimal numbers (uniform)
- Use a while not escape() loop
- Plot points on a “dart board”
- Display text on a plot screen
Intro 2
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.
Step 1
The plan:
- 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
Step 2
Begin a new program (PIDARTS) and get the three import statements from the <Fns…> Modul menus.
Step 3
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
Step 4
Make two variables for counting the darts and counting the hits.
Initialize both to 0.
hits = 0 # of darts inside the circle
total = 0 # of darts tossed
Step 5
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.
Step 6
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.
Step 7
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.
Step 8
Dedent (un-indent) the next line to exit the if block but remain in the while block. Plot the point.
Select
♦ ♦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.
Step 9
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.
Step 10
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.
Step 11
Adding
♦ ♦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.
Step 12
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
- Application
End of Course Projects
Extensions and More Practice
Download Student DocReady for more? Now that you have completed the course, you are ready to try your hand at some more challenges. Make sure you have completed all the Units prior to starting this section. The projects here will have you apply what you have already learned. Download the document here for challenges to choose from.
If you get stuck, refer back to the previous Units in the course. For an extra challenge, design your own program from scratch. If it’s really cool, post your work to social media and tag it @TICalculators. We would love to see your creativity. Good luck and get coding!