0% found this document useful (0 votes)
117 views

Python Cheat Sheet - StarLAB

This document provides a Python cheat sheet covering various Python concepts like variables, data types, printing, math operators, conditional statements, loops, functions, importing, lists, working with files, and interacting with StarLAB sensors and buttons. It defines key terms and shows examples of how to work with integers, floats, strings, booleans, conditionals, loops, functions, imports, lists, files, and StarLAB components in Python code.

Uploaded by

Alex
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views

Python Cheat Sheet - StarLAB

This document provides a Python cheat sheet covering various Python concepts like variables, data types, printing, math operators, conditional statements, loops, functions, importing, lists, working with files, and interacting with StarLAB sensors and buttons. It defines key terms and shows examples of how to work with integers, floats, strings, booleans, conditionals, loops, functions, imports, lists, files, and StarLAB components in Python code.

Uploaded by

Alex
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python Cheat Sheet http://starlab.

education
http://obelisksystems.com
If you need more help, just ask! [email protected]

Variables, Types, and Printing Things Maths Operators check = (temp >= 18) # check if the temp is above 18
if check: # test check
A variable holds some piece of data for you to use later. maths operations can be done using the built-in print (“It’s too hot!”) # run if check is True
They will have a type that is usually handled by Python, operators.
but it is useful to know about them. if statements can run other code if the test is False.
product = n + 1 # will have the sum of n and 1
Integers can be any whole number like -1, 0, 1, 2, 3 subtraction = n – 1 # one subtracted from n if temp < 4: # first test
multiply = n * 8 # eight times n print (“It’s too cold!”)
intNumber = 1 # assigns intNumber as 1 divide = n / 9 # division elif temp < 18: # only tests if the first is False
Floating point numbers are numbers like 1.01 divide = n//9 # integer division print (“This is nice!”)
remainder = n % 9 # remainder from division else: # run if the others are False
floatNumber = 1.00 # .00 makes it a float exponent = n ** 8 # n raised to the 8th power print (“It’s too hot!”)
Strings are text values and are set by using quotes (“ or ‘) Any maths operator can be used with the equals symbol Loops
msg = “Hello Space!” # assign String to msg to assign the vale and perform the operation A while loop repeats a block of code until a certain
You can output a variable with print product += 1 # product = product + 1 condition is true. Hint: If you get stuck in a loop try Ctrl-C

msg = “Hello Space!” # assign String to msg User Input counter = 1 # initialise counter
print (msg) # displays text in window while counter <= 5: # test if condition is reached
You can allow users to interact with your program with print (counter) # print the current value
you can output multiple values with a comma (,) inputs. raw_input will store the input as a string. counter += 1 # add one to the counter
firstName = “Ada” #Assign String to firstName name = raw_input(“Who. are. you?“) # caterpillar question Setting the condition for a while to True will make it loop
lastName = “Lovelace” #Assign String to lastName print (“Explain yourself, “+name+”!”) # his response infinitely.
print (“Countess”, firstName, lastName) Other data types are gotten with input; it will decide msg = “” # assign msg to be an empty string
You can change the type of a variable by ‘casting’ which type to use based on the input. while True: # Loop forever!
planets = input(“How many planets are there? “) # integer msg = raw_input(“Speak friend and enter”)
number = “1” # a String with the 1 character if msg == ‘mellon’:
number2 = 2 # the integer 2 print (planets) # print 8 (we love Pluto, but no)
pi = input(“What’s the value of pi?“) # floating point break # end the loop
print (number+number2) # will cause an error
print (int(number)+number2) # prints 3 pi = float(pi) # 3.14159265…How long can this go for? A for loop will run for a set number of times and then exit.
print (float(number)+number2) # prints 3.0 Booleans (True or False) for i in range(1, 6):
print (number+str(number2)) # prints 12
Booleans are a special type of variable that can either be print (“Loop number”, i)
Functions True or False
Working with Files
Functions let you use one block of code in many places. Blue = True # sets variable to True filename = ‘newFile.txt’ # set filename
Blue = False # sets variable to False myfile = open(filename, ’r’) # open file for reading
def add(x, y=2): # y=2 we set the default value
return x + y # add the inputs and return result Booleans can be used for conditional arguments. lines = myfile.readlines() # load lines into a list
print (add(1)) # call function : returns 3 for line in lines: # loop through lines
test = (n == 7) # True if n equal 7 print (line) # print each line
print (add(1,9)) # call function : returns 10 test = (n != 7) # True if n not equal 7
test = (n > 7) # True if n greater than 7 Writing to a file
Import
test = (n >= 7) # True if n greater than or equal 7 filename = ‘journal.txt’ # set filename
You can get extra functions by using import, there are test = (n < 7) # True if n less than 7 myfile = open(filename, ‘w’) # open file to write
many libraries you can import. test = (n <= 7) # True if n less than or equal 7 myfile.write(“I love programming.”) # write text to file
import time # import library If Statements Appending to a file:
n=0 # initialise counter
while True: # loop forever! If statements Use Booleans to perform small blocks of
filename = ‘journal.txt’ # set filename
print (n += 1) #add one code if a test is True or False.
myfile = open(filename, ‘a’) # open file to write
time.sleep(1) # pauses the loop for 1 second myfile.write(“\nI love making games.”)# write text to file
List StarLAB Spectrum Sensors StarLAB Buttons
A List stores a series of items in particular order. You The spectrum sensors get information about the light that The buttons on the StarLAB return a 1 when they are pressed
access items using an index, or within a loop. the StarLAB can see. getSpectrum() returns a list from all and 0 when they are not. The buttons can be checked all at
the sensors [[Red, Green, Blue], ambient, IR, UV] once with readButtonALL and returns the list [Left, Up, Down,
Make a list: Right, Centre, A, B, C]
data = myStarLAB.spectrum.getSpectrum() # all spectrum
lukeLunch = [‘carrot’, ‘broccoli’, ‘corn’] # define list data = myStarLAB.button.readAll() # all!
getRGB returns a list of [Red, Green, Blue] in lux
Get the first item in a list: Buttons can be checked individually using readButton<name>
data = myStarLAB.spectrum.getRGB() # RGB in lux where name is on of A, B, C, Up, Down, Left, Right, Centre.
first_lukeLunch = lukeLunch[0] # lists index from 0
getAmbient, spectrum.getIR, and spectrum.getUV return data = myStarLAB.button.readA() # just A
Get the last item in a list: a Single value in Lux for the first two and μW/cm^2 for UV
last_lukeLunch = lukeLunch[-1] # -1 is shorthand for last StarLAB OLED Screen
data1 = myStarLAB.spectrum.getAmbient() # Lux
Looping through a list: data2 = myStarLAB.spectrum.getIR() # Lux Write messages on the OED with writeText it takes a string
data3 = myStarLAB.spectrum.getUV() # μW/cm^2 input.
for veg in lukeLunch: # veg is the current element
print(veg) # displays element in window StarLAB Movement Sensors myStarLAB.OLED.writeText(“Hello Space”) # write hello

Adding items to a list: The IMU returns information about the movement of the Write each line of the OLED with writeTextLine where each line
starLAB. They all return a list of three dimensions [X,Y,Z] gets its own string.
lukeLunch = [] # define empty list
lukeLunch.append(‘carrot’) # add Element data1 = myStarLAB.IMU.getAccel() # m/(s^2) L1 = “Haikus are easy” # String for line 1
lukeLunch.append(‘broccoli’) # add Element data2 = myStarLAB.IMU.getGyro() # deg/s L2 = “But sometimes they” # String for line 2
lukeLunch.append(‘corn’) # add Element data3 = myStarLAB.IMU.getMag() # m-Gauss L3 = “Refrigerator” # String for line 3
data4 = myStarLAB.IMU.getOrientation() # deg myStarLAB.OLED.writeTextLine(Line1=L1,Line2=L2,Line3=L3)
Making numerical Lists:
StarLAB Atmospheric Sensors Clear the screen with clear
squares = [] # define empty list
for x in range(1, 11): The atmos sensors give you information about the myStarLAB.OLED.clear()
squares.append(x**2) # x^2 weather and are all single values.
StarLAB Camera
Slicing a list: data1 = myStarLAB.atmos.getHumidity() # percentage
data2 = myStarLAB.atmos.getPressure() # hPa Pictures can be taken with takePicture. The input will be the
students = [‘grace’, ‘alan’, ‘ada’,’nikola’] # define list data3 = myStarLAB.atmos.getAltitudeM() # meters name of the file in the location of the script.
first_two = students[:2] # ’:2’ selects everything before 2 data4 = myStarLAB.atmos.getTempC() # celsius myStarLAB.camera.takePicture(“filename”) # filename.jpg
Copying a list: StarLAB Hardware Temperature StarLAB Rover
copy_of_lunch = lukeLunch[:] # ‘:’ selects everything The temperature of the board can be gotten with Take control of the Rover with the new API.
Conditional test with lists: data1 = myStarLAB.boardThermo.getTopTempC() myStarLAB.enableRover() # enable control of the Rover
data2 = myStarLAB.boardThermo.getBotTempC()
‘broccoli’ in lukeLunch # True if broccoli in list See the power usage of the rover and StarLAB.
‘potato’ not in lukeLunch # True if potato not in list StarLAB LED Lights
data1 = myStarLAB.reactor.generator.getVoltage()
Connecting to StarLAB The StarLAB has 4 indicator LEDs (LED1-4) and one RGB
# battery Level in Volts
LED that is controlled by three values (Red, Green, and
Make sure you copy the StarLAB.pyc into the directory data2 = myStarLAB.reactor.engine.getCurrent()
Blue). To turn on or off any LED you use the set<name>On
that your python script is in. Then you can import the API. # motor current draw in mA
and set<name>Off. The RGB brightness is changed with
data3 = myStarLAB.reactor.processor.getPower()
import StarLAB # import the best library set<name> with 0 being off and 255 being maximum.
# power used by the Rover in mW
Connect to the StarLAB with the IP on the OLED. myStarLAB.light.setRedOn() # turn on Red
myStarLAB.light.setGreenOff() # turn off Green
Set the motor power.
myStarLAB = StarLAB.Connect(IP = “192.168.0.1”) myStarLAB.light.setBlue(175) # set brightness of Blue myStarLAB.motors.setMotorPower(60,60) # move forward
When connecting to multiple StarLABs use different myStarLAB.motors.setMotorPower(-40,-40)# move backwards
StarLAB Buzzer myStarLAB.motors.turnRover(90) # turn by angle
names for each one.
To turn on the buzzer set the frequency using setFrequency.
myStarLAB = StarLAB.Connect(IP = “192.168.0.1”) This command takes an input between 0-8000Hz. Setting Get the distance from an obstacle.
lukeStarLAB = StarLAB.Connect(IP = “192.168.0.2”) a value of 0 will turn the buzzer off. data1 = myStarLAB.ranger.getDistance() # range in cm
myStarLAB.buzzer.setFrequency(880) # buzzer in Hz
myStarLAB.buzzer.setFrequency(0) # turn buzzer off

You might also like