TI-Nspire Python Programming Guidebook En
TI-Nspire Python Programming Guidebook En
Programming Guidebook
i
Contents
Python Workspaces 3
Python Editor 3
Python Shell 8
Appendix 41
Python Keywords 41
Python Key Mapping 41
Sample Python Programs 43
General Information 51
ii
Getting Started with Python Programming
Using Python with TI-Nspire™ products you can:
• add Python programs to TNS files
• create Python programs using templates
• interact and share data with other TI-Nspire™ apps
• interact with the TI-Innovator™ Hub and TI-Innovator™ Rover
The TI-Nspire™ Python implementation is based on MicroPython, which is a small
subset of the Python 3 standard library designed to run on microcontrollers. The
original MicroPython implementation has been adapted for use by TI.
Note: Some numeric answers may vary from the Calculator results due to differences in
the underlying math implementations.
Python is available on these TI-Nspire™ products:
Note: In most cases, functionality is identical between the handheld and the software
views, but you may see some differences. This guide assumes that you are using the
handheld device or the Handheld view in the software.
Python Modules
TI-Nspire™ Python includes the following modules:
Note: If you have existing Python programs created in other Python development
environments, you may need to edit them to run on the TI-Nspire™ Python solution.
Modules may use different methods, arguments, and ordering of methods in a program
For a list of menus with their items and descriptions, please see the Menu Map section.
Python Editor
The Python Editor is where you can create, edit and save Python programs.
Adding a Python Editor page
To add a new Python Editor page in the current problem, press b and select Add
Python > New.
3 Python Workspaces
After creating the program, the Python Editor is displayed. If you selected a template,
the necessary import statements are automatically added (see below).
Note: You can have multiple programs in a single TNS file just like other apps. If the
Python program is intended to be used as a module, the TNS file can be saved in the
PyLib folder. That module can then be used in other programs and documents.
Python Workspaces 4
Opening a Python Program
To open an existing Python program, press ~ and select Insert > Add Python > Open.
This will display a list of programs that have been saved in the TNS file.
If the Editor page used to create the program has been deleted, the program is still
available in the TNS file.
Working in the Python Editor
Pressing b displays the Document Tools menu. With these menu options you can
add, move, and copy blocks of code for your program.
Items selected from the module menus will automatically add a code template to the
Editor with inline prompts for each part of the function. You can navigate from one
argument to the next by pressing e (forward) or g+e (backward). Tooltips or
pop-up lists will appear when available to help you select the proper values.
Pop-up lists
The numbers to the right of the program name reflect the current line number of the
cursor and the total number of lines in the program.
5 Python Workspaces
Global functions and variables defined in the lines above the current cursor position
can be inserted by pressing h and selecting from the list.
As you add code to your program, the Editor displays keywords, operators, comments,
strings and indents in different colors to aid in identifying the different elements.
Pasted menu items are placed on current line or next line based on context.
The main menu displays the module menu based on the program being edited
providing quicker access to those options. Only one module is displayed at a time.
Python Workspaces 6
The Edit menu displays commonly used menu items and shortcuts.
To run the program, press b and select Run > Run. This will run the current program
in the next Python Shell page or a new one if the next page is not a Shell.
Note: Running the program automatically checks the syntax and saves the program.
7 Python Workspaces
Python Shell
The Python Shell is the interpreter that executes your Python programs, other pieces of
Python code, or simple commands.
The Python Shell can also be launched from the Python Editor by executing a program
by pressing b and selecting Run > Run.
Python Workspaces 8
Note: If you use any method from one of the available modules, be sure to execute an
import module statement first as in any Python coding environment.
Interaction with the Shell output is similar to the Calculator app where you can select
and copy previous inputs and outputs for use elsewhere in the Shell, Editor, or other
apps.
Up arrow to select, then copy and paste to the desired location
Global functions and variables from the last run program can be inserted by pressing
h or /+L and selecting from the list or press b and select Variables > Vars: Last
Run Program.
To choose from a list of global functions and variables from both the last run program
and any imported modules, press b and select Variables > Vars: All.
Variables menu
All Python Shell pages in the same problem share the same state (user-defined and
imported variable definitions). When you save or run a Python program in that
problem, or press b and select Tools > Reinitialize Shell, the Shell history will then
have a gray background indicating that the previous state is no longer valid.
9 Python Workspaces
Before saving or reinitializing After saving or reinitializing
Note: The b Tools > Clear History option clears the screen of any previous activity in
the Shell, but variables are still available.
Messages
Error and other informational messages may display while you are in a Python session.
If an error is displayed in the Shell when a program executes, a program line number
will display. Press / b and select Go to Python Editor. In the Editor, press b then
select Edit > Go to Line. Enter the line number and press ·. The cursor will display on
the first character of the line where the error occurred.
Interrupting a Running Program
Python Workspaces 10
Python Menu Map
This section lists all of the menus and menu items for the Python Editor and Shell and a
brief description for each one.
Note: For the menu items that have keyboard shortcuts, Mac® users should substitute
“ (Cmd) anywhere Ctrl is used. For a complete list of TI-Nspire™ handheld and
software shortcuts, see the TI-Nspire™ Technology eGuide.
Actions Menu 11
Run Menu 12
Tools Menu 12
Edit Menu 13
Built-ins Menu 15
Math Menu 17
Random Menu 18
TI PlotLib Menu 19
TI Hub Menu 20
TI Rover Menu 28
Complex Math Menu 35
Time Menu 35
TI System Menu 36
TI Draw Menu 37
TI Image Menu 39
Variables Menu 40
Actions Menu
Note: This applies to the Editor only.
Item Description
New Opens the New dialog box where you enter a name and select a type
for your new program.
Open Opens a list of programs available in the current document.
Create Copy Opens the Create Copy dialog box where you can save the current
program under another name.
Rename Opens the Rename dialog box where you can rename the current
Run Menu
Note: This applies to the Editor only.
Tools Menu
Note: This applies to the Shell only.
Edit Menu
Note: Ctrl+A selects all lines of code or output for cutting or deleting (Editor only), or
copying and pasting (Editor and Shell).
Item Description
def function(): Defines a function dependent on specified variables.
return Defines the value produced by a function.
Control
Item Description
if.. Conditional statement.
if..else.. Conditional statement.
if..elif..else.. Conditional statement.
for index in range(size): Iterates over a range.
for index in range(start,stop): Iterates over a range.
for index in range(start,stop,step): Iterates over a range.
for index in list: Iterates over list elements.
while.. Executes statements in a code block until a
condition evaluates to False.
elif: Conditional statement.
else: Conditional statement.
Ops
Item Description
x=y Sets variable value.
x==y Pastes equal to (==) comparison operator.
x!=y Pastes not equal to (!=) comparison operator.
x>y Pastes greater than (>) comparison operator.
x>=y Pastes greater than or equal to (>=) comparison operator.
x<y Pastes less than (<) comparison operator.
x<=y Pastes less than or equal to (<=) comparison operator.
Lists
Item Description
[] Pastes brackets ([]).
list() Converts sequence into "list" type.
len() Returns number of elements of the list.
max() Returns maximum value in the list.
min() Returns minimum value in the list.
.append() The method appends an element to a list.
.remove() The method removes the first instance of an
element from a list.
range(start,stop,step) Returns a set of numbers.
for index in range(start,stop,step) Used to iterate over a range.
.insert() The method adds an element at the specified
position.
.split() The method returns a list with elements
separated by specified delimiter.
sum() Returns sum of the elements of a list.
sorted() Returns a sorted list.
.sort() The method sorts a list in place.
Type
Item Description
int() Returns an integer part.
float() Returns a float value.
I/O
Item Description
print() Displays argument as string.
input() Prompts user for input.
eval() Evaluates an expression represented as a string.
.format() The method formats the specified string.
Math Menu
Note: When creating a new program that uses this module, it is recommended to use
the Math Calculations program type. This will ensure that all the relevant modules are
imported.
Item Description
from math import * Imports all methods (functions) from the math module.
fabs() Returns absolute value of a real number.
sqrt() Returns square root of a real number.
exp() Returns e**x.
pow(x,y) Returns x raised to the power y.
log(x,base) Returns logbase(x).
log(x) with no base returns the natural logarithm x.
fmod(x,y) Returns module value of x and y. Use when x and y are floats.
ceil() Returns the smallest integer greater than or equal to a real
number.
floor() Returns the largest integer less than or equal to a real
number.
trunc() Truncates a real number to an integer.
frexp() Returns a pair (y,n) where x == y * 2**n.
Item Description
e Returns value for the constant e.
pi Returns value for the constant pi.
Trig
Item Description
radians() Converts angle in degrees to radians.
degrees() Converts angle in radians to degrees.
sin() Returns sine of argument in radians.
cos() Returns cosine of argument in radians.
tan() Returns tangent of argument in radians.
asin() Returns arc sine of argument in radians.
acos() Returns arc cosine of argument in radians.
atan() Returns arc tangent of argument in radians.
atan2(y,x) Returns arc tangent of y/x in radians.
Random Menu
Note: When creating a new program that uses this module, it is recommended to use
the Random Simulations program type. This will ensure that all the relevant modules
are imported.
Item Description
from random import * Imports all methods from the random module.
random() Returns a floating point number from 0 to 1.0.
uniform(min,max) Returns a random number x (float) such that min <= x
<= max.
randint(min,max) Returns a random integer between min and max.
choice(sequence) Returns a random element from a non-empty
sequence.
randrange(start,stop,step) Returns a random number from start to stop by step.
TI PlotLib Menu
Note: When creating a new program that uses this module, it is recommended to use
the Plotting (x,y) & Text program type. This will ensure that all the relevant modules are
imported.
Item Description
import ti_plotlib as plt Imports all methods (functions) from the ti_plotlib module
in the "plt" namespace. As a result, all function names
pasted from the menus will be preceded by "plt.".
Setup
Item Description
cls() Clears the plotting canvas.
grid(x-scale,y-scale,"style") Displays a grid using specified scale for x and y
axes.
window(xmin,xmax,ymin,ymax) Defines the plotting window by mapping the the
specified horizontal interval (xmin, xmax) and
vertical interval (ymin, ymax) to the allotted
plotting area (pixels).
auto_window(x-list,y-list) Autoscales the plotting window to fit the data
ranges within x-list and y-list specified in the
program prior to the auto_window().
axes("mode") Displays axes on specified window in the plotting
area.
labels("x-label","y-label",x,y) Displays "x-label" and "y-label" labels on the plot
axes at row positions x and y.
title("title") Displays "title" centered on top line of window.
show_plot() Displays the buffered drawing output.
The use_buffer() and show_plot() functions are
useful in cases where displaying multiple objects
on the screen could cause delays (not necessary in
most cases).
use_buffer() Enables an off-screen buffer to speed up drawing.
Item Description
color(red,green,blue) Sets the color for all following graphics/plotting.
cls() Clears the plotting canvas.
show_plot() Executes the display of the plot as set up in the
program.
scatter(x-list,y-list,"mark") Plots a sequence of ordered pair from (x-list,y-list)
with the specified mark style.
plot(x-list,y-list,"mark") Plots a line using ordered pairs from specified x-list
and y-list.
plot(x,y,"mark") Plots a point using coordinates x and y with the
specified mark style.
line(x1,y1,x2,y2,"mode") Plots a line segment from (x1,y1) to (x2,y2).
lin_reg(x-list,y-list,"display") Calculates and draws the linear regression model,
ax+b, of x-list,y-list.
pen("size","style") Sets the appearance of all following lines until the
next pen() is executed.
text_at(row,"text","align") Displays "text" in plotting area at specified "align".
Properties
Item Description
xmin Specified variable for window arguments defined as plt.xmin.
xmax Specified variable for window arguments defined as plt.xmax.
ymin Specified variable for window arguments defined as plt.ymin.
ymax Specified variable for window arguments defined as plt.ymax.
m After plt.linreg() is executed in a program, the computed values of slope, m,
and intercept, b, are stored in plt.m and plt.b.
b After plt.linreg() is executed in a program, the computed values of slope, a,
and intercept, b, are stored in plt.a and plt.b.
TI Hub Menu
Note: When creating a new program that uses this module, it is recommended to use
the Hub Project program type. This will ensure that all the relevant modules are
imported.
Item Description
rgb(red,green,blue) Sets the color for the RGB LED.
blink(frequency,time) Sets the blinking frequency and duration for the selected
color.
off() Turns the RGB LED off.
Item Description
on() Turns the LED on.
off() Turns the LED off.
blink(frequency,time) Sets the blinking frequency and duration for the LED.
Item Description
tone(frequency,time) Plays a tone of the specified frequency for the
specified time.
note("note",time) Plays the specified note for the specified time.
The note is specified using the note name and an
octave. For example: A4, C5.
The note names are C, CS, D, DS, E, F, FS, G, GS, A, AS,
and B.
The octave numbers range from 1 to 9 (inclusive).
tone(frequency,time,tempo) Plays a tone of the specified frequency for the
specified time and tempo.
The tempo defines the number of beeps per second
ranging from 0 to 10 (inclusive).
note("note",time,tempo) Plays the specified note for the specified time and
tempo.
Item Description
measurement() Reads the built-in BRIGHTNESS (light level) sensor and returns a
reading.
The default range is 0 to 100. This can be changed using the range
() function.
range(min,max) Sets the range for mapping the readings from the light level
sensor.
If both are missing, or set to a value of None, then the default
brightness range of 0 to 100 is set.
Item Description
DHT (Digital Humidity & Temp) Returns a list consisting of the current
temperature, humidity, type of sensor, and last
cached read status.
Ranger Returns the current distance measurement from
the specified ultrasonic ranger.
• measurement_time() - Returns the time that
the ultrasonic signal takes to reach the object
(the "time of flight").
Light Level Returns the brightness level from the external light
level (brightness) sensor.
Temperature Returns the temperature reading from the external
temperature sensor.
Item Description
LED Functions for controlling externally connected LEDs.
RGB Support for controlling external RGB LEDs.
TI-RGB Array Provides functions for programming the TI-RGB Array.
Speaker Functions for supporting an external speaker with the TI-
Innovator™ Hub.
The functions are the same as the ones for "sound" above.
Power Functions for controlling external power with the TI-Innovator™
Hub.
• set(value): Sets the Power level to the specified value,
between 0 and 100.
• on(): Sets the Power level to 100.
• off(): Sets the Power level to 0.
Continuous Servo Functions for controlling continuous servo motors.
• set_cw(speed,time): The servo will spin in the clockwise
direction at the specified speed (0-255) and for the specific
duration in seconds.
• set_ccw(speed,time): The servo will spin in the counter-
clockwise direction at the specified speed (0-255) and for
the specific duration in seconds.
• stop(): Stops the continuous servo.
Analog Out Functions for the use of analog input generic devices.
Vibration Motor Functions for controlling vibration motors.
• set(val): Sets the vibration motor intensity to "val" (0-255).
• off(): Turns the vibration motor off.
• on(): Turns the vibration motor on at the highest level.
Relay Controls interfaces for controlling relays.
• on(): Sets the relay to the ON state.
• off(): Sets the relay to the OFF state.
Servo Functions for controlling servo motors.
• set_position(pos): Sets the sweep servo position within a
range of -90 to +90.
• zero(): Sets the sweep servo to the zero position.
Squarewave Functions for generating a square wave.
Commands
Item Description
sleep(seconds) Pauses the program for the specified number of
seconds.
Imported from the 'time' module.
text_at(row,"text","align") Displays the specified "text" in the plotting area at
specified "align".
Part of the ti_plotlib module.
cls() Clears the Shell screen for plotting.
Part of the ti_plotlib module.
while get_key() != "esc": Runs the commands in the "while" loop until the "esc"
key is pressed.
get_key() Returns a string representing the key pressed.
The '1' key returns "1", 'esc' returns "esc", and so on.
When called without any parameters - get_key() - it
returns immediately.
When called with a parameter - get_key(1) - it waits
until a key is pressed.
Part of the ti_system module.
Ports
These are the input and output ports available on the TI-Innovator™ Hub.
TI Rover Menu
Note: When creating a new program that uses this module, it is recommended to use
the Rover Coding program type. This will ensure that all the relevant modules are
imported.
Item Description
import ti_rover as rv Imports all methods (functions) from the ti_rover module in
the "rv" namespace. As a result, all function names pasted
from the menus will be preceded by "rv.".
Drive
Item Description
forward(distance) Moves Rover forward the specified distance in grid
units.
backward(distance) Moves Rover backward the specified distance in grid
Item Description
forward_time(time) Moves Rover forward for the specified
time.
backward_time(time) Moves Rover backward for the specified
time.
forward(distance,"unit") Moves Rover forward at the default speed
for the specified distance.
The distance can be specified in grid units,
meters, or wheel revolutions.
backward(distance,"unit") Moves Rover backward at the default
speed for the specified distance.
The distance can be specified in grid units,
meters, or wheel revolutions.
left(angle,"unit") Turns Rover left the specified angle.
The angle can be in degrees, radians, or
gradians.
Inputs
Item Description
ranger_measurement() Reads the ultrasonic distance sensor on the front
of the Rover, returning the current distance in
meters.
color_measurement() Returns a value from 1 to 9, indicating the
predominant color being "seen" by the Rover color
input sensor.
1 = red
2 = green
3 = blue
4 = cyan
5 = magenta
6 = yellow
Outputs
Item Description
color_rgb(r,g,b) Sets the color of the Rover RGB LED to
the specific red, green, blue values.
color_blink(frequency,time) Sets the blinking frequency and
duration for the selected color.
color_off() Turns the Rover RGB LED off.
motor_left(speed,time) Sets the left motor power to the
specified value for the specified
duration.
The speed is in the range -255 to 255
with 0 being stop. Positive speed values
are counter-clockwise rotation, and
negative speed values are clockwise.
Path
Item Description
waypoint_xythdrn() Reads the x-coord, y-coord, time, heading, distance traveled,
number of wheel revolutions, command number of the
current waypoint. Returns a list with all these values as
elements.
waypoint_prev Reads the x-coord, y-coord, time, heading, distance traveled,
number of wheel revolutions, command number of the
previous waypoint.
waypoint_eta Returns the estimated time to drive to a waypoint.
path_done() Returns a value of 0 or 1 depending on whether the Rover is
moving (0) or finished with all movement (1).
Settings
Item Description
units/s Option for speed in grid units per second.
m/s Option for speed in meters per second.
revs/s Option for speed in wheel revolutions per second.
units Option for distance in grid units.
m Option for distance in meters.
revs Option for distance in wheel revolutions.
degrees Option for turning in degrees.
Commands
These commands are collection of functions from other modules as well as from the TI
Rover module.
Item Description
sleep(seconds) Pauses the program for the specified number of
seconds.
Imported from the time module.
text_at(row,"text","align") Displays "text" in plotting area at specified "align".
Imported from the ti_plotlib module.
cls() Clears the Shell screen for plotting.
Imported from the ti_plotlib module.
while get_key() != "esc": Runs the commands in the "while" loop until the "esc"
key is pressed.
wait_until_done() Pauses the program until the Rover finishes the
current command.
This is a helpful way to synchronize non-Rover
commands with Rover's motion.
while not path_done() Runs the commands in the "while" loop until the
Rover is finished with all movement.
The path_done() function returns a value of 0 or 1
depending on whether the Rover is moving (0) or
finished with all movement (1).
position(x,y) Sets the Rover position on the virtual grid to the
specified x,y coordinate.
position(x,y,heading,"unit") Sets the Rover position on the virtual grid to the
specified x,y coordinate, and the virtual heading,
relative to the virtual x-axis is set if a heading is
provided (in the units for angles specified).
Positive angles from 0 to 360 are assumed to be
counter-clockwise from the positive x axis. Negative
angles from 0 to -360 are assumed to be clockwise
from the positive x axis.
Item Description
from cmath import * Imports all methods from the cmath module.
complex(real,imag) Returns a complex number.
rect(modulus,argument) Converts polar coordinates to rectangular form of a
complex number.
.real Returns real part of the complex number.
.imag Returns imaginary part of a complex number.
polar() Converts rectangular form to polar coordinates of a
complex number.
phase() Returns phase of a complex number.
exp() Returns e**x.
cos() Returns cosine of a complex number.
sin() Returns sine of a complex number.
log() Returns natural logarithm of a complex number.
log10() Returns base 10 logarithm of a complex number.
sqrt() Returns square root of a complex number.
Time Menu
This submenu is located under More Modules.
Item Description
from time import * Imports all methods from the time module.
TI System Menu
This submenu is located under More Modules.
Note: When creating a new program that uses this module, it is recommended to use
the Data Sharing program type. This will ensure that all the relevant modules are
imported.
Item Description
from ti_system import * Imports all methods (functions) from the ti_system
module.
recall_value("name") Recalls a predefined OS variable (value) named
"name".
store_value("name",value) Stores a Python variable (value) to an OS variable
named "name".
recall_list("name") Recalls a predefined OS list named "name".
store_list("name",list) Stores a Python list (list) to an OS list variable named
"name".
eval_function("name",value) Evaluates a predefined OS function at the specified
value.
get_platform() Returns "hh" for handheld and "dt" for desktop.
get_key() Returns a string representing the key pressed.
The '1' key returns "1", 'esc' returns "esc", and so on.
TI Draw Menu
This submenu is located under More Modules.
Note: When creating a new program that uses this module, it is recommended to use
the Geometry Graphics program type. This will ensure that all the relevant modules are
imported.
Item Description
from ti_draw import * Imports all methods from the ti_draw module.
Shape
Item Description
draw_line() Draws a line starting from the specified x1,y1 coordinate to x2,y2.
draw_rect() Draws a rectangle starting at the specified x,y coordinate with the
specified width and height.
fill_rect() Draws a rectangle starting at the specified x,y coordinate with the
specified width and height and filled with the specified color (using
set_color or black if not defined).
draw_circle() Draws a circle starting at the specified x,y center coordinate with the
specified radius.
fill_circle() Draws a circle starting at the specified x,y center coordinate with the
specified radius and filled with the specified color (using set_color or
Control
Item Description
clear() Clears the entire screen. Can be used with x,y,width,height
parameters to clear an existing rectangle.
clear_rect() Clears the rectangle at the specified x,y coordinate with the
specified width and height.
set_color() Sets the color of the shape(s) that follow in the program until
another color is set.
set_pen() Sets the specified thickness and style of the border when
drawing shapes (not applicable when using fill commands).
set_window() Sets the size of the window in which any shapes will be drawn.
This function is useful to resize the window to match the data or
to change the origin (0,0) of the drawing canvas.
get_screen_dim() Returns the xmax and ymax of the screen dimensions.
use_buffer() Enables an off-screen buffer to speed up drawing.
paint_buffer() Displays the buffered drawing output.
Notes
• The default configuration has (0,0) in the top left corner of the screen. The positive
x-axis points to the right and the positive y-axis points to the bottom This can be
modified by using the set_window() function.
• The functions in ti_draw module are only available on the handheld and in
handheld view on desktop.
TI Image Menu
This submenu is located under More Modules.
Note: When creating a new program that uses this module, it is recommended to use
the Image Processing program type. This will ensure that all the relevant modules are
imported.
Item Description
from ti_image import * Imports all methods from the ti_image module.
new_image(width,height,(r,g,b)) Creates a new image with the specified width and
height for use in the Python program.
The color of the new image is defined by the
(r,g,b) values.
load_image("name") Loads the image specified by the "name" for use
in the Python program.
The image must be part of the TNS document
either in a Notes or Graphs application.
The "name" prompt will display the image names
(if they have been named earlier) or a number
indicating their insertion order.
copy_image(image) Creates a copy of the image specified by the
"image" variable.
Variables Menu
Note: These lists do not include variables defined in any other TI-Nspire™ apps.
Item Description
Vars: Current Program (Editor only) Displays a list of global functions and variables
defined in the current program
Vars: Last Run Program (Shell only) Displays a list of global functions and variables
defined in the last run program
Vars: All (Shell only) Displays a list of global functions and variables
from both the last run program and any imported modules
Python Keywords
The following keywords are built into the TI-Nspire™ Python implementation.
Key Mapping
h Opens Variables menu
Ë Pastes = sign
. Deletes character to the left of the cursor
Ì No action
= Pastes = sign
Í Pastes the selected symbol(s):
• >
• <
• !=
41 Appendix
Key Mapping
• >=
• <=
• ==
• and
• or
• not
• |
• &
• ~
µ Pastes the selected function:
• sin
• cos
• tan
• atan2
• asin
• acos
• atan
Î Displays hints
Ï Pastes :=
l Pastes **
Ñ No action
q Pastes **2
Ò Pastes sqrt()
r Pastes multiply sign (*)
Ó Pastes one double quote (")
p Pastes division sign (/)
Ô No action
u Pastes exp()
Õ Pastes log()
s Pastes 10**
Ö Pastes log(value,base)
( Pastes (
) Pastes )
Appendix 42
Key Mapping
Û Pastes [ ]
Ú Pastes { }
v Pastes subtract sign (-)
Þ Adds a new line after the current line
i Pastes E
º Pastes the selected symbol(s):
• ?
• !
• $
• °
• '
• %
• "
• :
• ;
• _
• \
• #
¹ Pastes "pi"
; Existing flag behavior
@ Adds a new line after the current line
43 Appendix
Appendix 44
Loop Example
# This program uses a "for" loop to calculate
# the squares and cubes of the first 5 numbers
# 0,1,2,3,4
# Note: Python starts counting at 0
for index in range(5):
••square = index**2
••cube = index**3
••print("Index: ", index, "Square: ", square,
••••"Cube: ", cube)
45 Appendix
Heads or Tails
# Use random numbers to simulate a coin flip
# We will count the number of heads and tails
# Run the program here by typing "Ctrl R"
# Import all the functions of the "random" module
from random import *
# n is the number of times the die is rolled
def coin_flip(n):
••••heads = tails = 0
••for i in range(n):
# Generate a random integer - 0 or 1
# "0" means head, "1" means tails
••••side=randint(0,1)
••••if (side == 0):
••••••heads = heads + 1
••••else:
••••••tails = tails + 1
# Print the total number of heads and tails
••print(n, "coin flips: Heads: ", heads, "Tails: ", tails)
print("\nPress the Var key and select 'coin_flip()'")
print("In the ( ), enter a number of flips!")
Appendix 46
Plotting
# Plotting example
import ti_plotlib as plt
# Set up the graph window
plt.window(-10,10,-10,10)
plt.axes("on")
plt.grid(1,1,"dashed")
# Add leading spaces to position the title
plt.title(" TITLE")
# Set the pen style and the graph color
plt.pen("medium","solid")
plt.color(28,242,221)
plt.line(-5,5,5,-5,"arrow")
plt.pen("thin","dashed")
plt.color(224,54,243)
plt.line(-5,-5,5,5,"")
# Scatter plot from 2 lists
plt.color(0,0,0)
xlist=[1,2,3,4,5]
ylist=[5,4,3,2,1]
plt.scatter(xlist,ylist, "x")
47 Appendix
Drawing
from ti_draw import *
# (0,0) is in top left corner of screen
# Let's draw some circles and squares
# Circle with center at (50,50) and radius 40
draw_circle(50,50,40)
# Set color to red (255,0,0) and fill a rectangle of
# of width 180, height 80 with top left corner at
# (100,100)
set_color(255,0,0)
fill_rect(100,100,180,80)
# Set color to green and pen style to "thin"
# and "dotted".
# Then, draw a circle with center at (200,100)
# and radius 40
set_color(0,255,0)
set_pen("thin","dotted")
draw_circle(200,100,40)
set_color(0,0,0)
draw_text(20,200,"Press Enter to exit")
Appendix 48
Image
# Image Processing
#================================
from ti_image import *
from ti_draw import *
#================================
# Load and show the 'manhole_cover' image
# It's in a Notes app
# Draw a circle on top
im1=load_image("manhole_cover")
im1.show_image(0,0)
set_color(0,255,0)
set_pen("thick","dashed")
draw_circle(140,110,100)
49 Appendix
Hub
This program uses Python to control the TI-Innovator™ Hub, a programmable
microcontroller. Running the program without attaching a TI-Innovator™ Hub will
display an error message.
For more information about TI-Innovator™ Hub, visit education.ti.com.
#========== Import Section ==========
from ti_hub import *
from math import *
from random import *
from time import sleep
from ti_plotlib import text_at,cls
from ti_system import get_key
#======== End of Import Section =======
print("Connect the TI-Innovator Hub and hit 'enter'")
input()
print("Blinking the RGB LED for 4 seconds")
# Set the RGB LED on the Hub to purple
color.rgb(255,0,255)
# Blink the LED 2 times a second for 4 seconds
color.blink(2,4)
sleep(5)
print("The brightness sensor reading is: ", brightness.measurement())
# Generate 10 random colors for the RGB LED
# Play a tone on the Hub based on the random
# color
print("Generate 10 random colors on the Hub & play a tone")
for i in range(10):
••r=randint(0,255)
••b=randint(0,255)
••g=randint(0,255)
••color.rgb(r,g,b)
••sound.tone((r+g+b)/3,1)
••sleep(1)
color.off()
Appendix 50
General Information
Online Help
education.ti.com/eguide
Select your country for more product information.
Contact TI Support
education.ti.com/ti-cares
Select your country for technical and other support resources.
51 General Information